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

前端 未结 4 1098
执笔经年
执笔经年 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:33

    public List findMatchingClicks(List cmps, List clicks) {
        List cmpsProspective = cmps.stream().filter(cmp -> "prospective".equals(cmp.type)).collect(Collectors.toList());
        return clicks.stream().filter(c -> matchesAnyCmp(c, cmpsProspective).collect(Collectors.toList());
    }
    
    public boolean matchesAnyCmp(Click click, List cmps) {
         return cmps.stream().anyMatch(click -> cmp.start.before(click.date) && cmp.end.after(click.date));
    }
    

    Replace fields for getters, just wrote it quick.

提交回复
热议问题