Java 8 streams: find items from one list that match conditions calculated based on values from another list

前端 未结 4 1097
执笔经年
执笔经年 2021-02-04 03:42

Have two classes and two corresponding lists:

class Click {
   long campaignId;
   Date date;
}

class Campaign {
   long campaignId;
   Date start;
   Date end;         


        
4条回答
  •  走了就别回头了
    2021-02-04 04:40

    Well, there is a very neat way to solve your problem IMO, original idea coming from Holger (I'll find the question and link it here).

    You could define your method that does the checks (I've simplified it just a bit):

    static boolean checkClick(List campaigns, Click click) {
        return campaigns.stream().anyMatch(camp -> camp.getCampaignId() 
                   == click.getCampaignId());
    }
    

    And define a function that binds the parameters:

    public static  Predicate bind(BiFunction f, T t) {
        return u -> f.apply(t, u);
    }
    

    And the usage would be:

    BiFunction, Click, Boolean> biFunction = YourClass::checkClick;
    Predicate predicate = bind(biFunction, campaigns);
    
    clicks.stream()
          .filter(predicate::test)
          .collect(Collectors.toList());
    

提交回复
热议问题