使用Java 8过滤对象列表 | 对子对象进行过滤 | Streams

huangapple go评论103阅读模式
英文:

Filter List of objects using java 8 | Filter on child objects | Streams

问题

我想要拥有有效优惠券的人员列表,即它应该满足条件:CURRENT_TIMESTAMPofferStartDateofferEndDate 之间。您能告诉我如何在 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&lt;BankAccounts&gt; listOfAccounts;
    
    //Getter and Setter
}

class BankAccounts {
    
    private String bankName;
    private String IFSC;

    @OneToMany(cascade = CascadeType.ALL)
    List&lt;OfferVoucher&gt; 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&lt;Person&gt; validPersons = persons.stream()
    .filter(p -&gt; p.getListOfAccounts().stream()
            .map(BankAccounts::getOffers)
            .flatMap(List::stream)
            .allMatch(o -&gt; o.getOfferStartDate() &lt; CURRENT_TIMESTAMP &amp;&amp; o.getOfferEndDate() &gt; 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.

huangapple
  • 本文由 发表于 2020年9月28日 17:23:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64099390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定