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

Viewed 55398

Have two classes and two corresponding lists:

class Click {
   long campaignId;
   Date date;
}

class Campaign {
   long campaignId;
   Date start;
   Date end;
   String type;
}

List<Click> clicks = ..;
List<Campaign> campaigns = ..;

And want to find all Clicks in clicks that:

  1. Have a corresponding Campaign in campaigns list, i.e., Campaign with the same campaignId AND

  2. This Campaign has type = "prospective" AND

  3. This Campaigns.start < click.date < Campaigns.end

So far I have the following implementation (which seems confusing and complex to me):

clicks.
        stream().
        filter(click -> campaigns.stream().anyMatch(
                campaign -> campaign.getCampaignType().equals("prospecting") &&
                        campaign.getCampaignId().equals(click.getCampaignId()) &&
                        campaign.getStart().after(click.getDate()) &&
                        campaign.getEnd().before(click.getDate()))).
        collect(toList());

I wonder if there is simpler solution for the problem.

4 Answers
Related