英文:
Filter List of objects using java 8 | Filter on child objects | Streams
问题
我想要拥有有效优惠券的人员列表,即它应该满足条件:CURRENT_TIMESTAMP
在 offerStartDate
和 offerEndDate
之间。您能告诉我如何在 Java 8 中实现这一点吗?
class Person {
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
List<BankAccounts> listOfAccounts;
//Getter and Setter
}
class BankAccounts {
private String bankName;
private String IFSC;
@OneToMany(cascade = CascadeType.ALL)
List<OfferVoucher> offers;
//Getter and Setter
}
class OfferVoucher {
int amount;
Date offerStartDate;
Date offerEndDate;
//other entities
//setter and getter
}
英文:
I want list of persons who has the valid offer voucher i.e it should satisfy the condition
CURRENT_TIMESTAMP
between offerStartDate
and offerEndDate
. Can you tell me how I can achieve this using java 8?
class Person {
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
List<BankAccounts> listOfAccounts;
//Getter and Setter
}
class BankAccounts {
private String bankName;
private String IFSC;
@OneToMany(cascade = CascadeType.ALL)
List<OfferVoucher> offers;
//Getter and Setter
}
class OfferVoucher {
int amount;
Date offerStartDate;
Date offerEndDate;
//other entities
//setter and getter
}
答案1
得分: 1
List<Person> validPersons = persons.stream()
.filter(p -> p.getListOfAccounts().stream()
.map(BankAccounts::getOffers)
.flatMap(List::stream)
.allMatch(o -> o.getOfferStartDate() < CURRENT_TIMESTAMP && o.getOfferEndDate() > CURRENT_TIMESTAMP))
.collect(Collectors.toList());
如果我正确理解问题,这应该可以工作。根据您的需求,您可能想要使用 `anyMatch` 而不是 `allMatch`。我还将日期处理为 `Long`,因此您可能需要根据您的应用程序以及实际实现进行更新。
英文:
List<Person> validPersons = persons.stream()
.filter(p -> p.getListOfAccounts().stream()
.map(BankAccounts::getOffers)
.flatMap(List::stream)
.allMatch(o -> o.getOfferStartDate() < CURRENT_TIMESTAMP && o.getOfferEndDate() > CURRENT_TIMESTAMP))
.collect(Collectors.toList());
If I understand the question correctly, this should work. You might want to use anyMatch
instead of allMatch
, depending on what you want exactly. I also have handled dates as Long
, so you may have to update this part, based on your application and how you implement it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论