java条件查询另一张表的,Java 8流:从一个列表中查找与根据另一列表中的值计算得出的条件相匹配的项目...

Have two classes and two corresponding lists:

class Click {

long campaignId;

Date date;

}

class Campaign {

long campaignId;

Date start;

Date end;

String type;

}

List clicks = ..;

List campaigns = ..;

And want to find all Clicks in clicks that:

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

This Campaign has type = "prospective" AND

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.

解决方案

One thing that stands out is that your 2nd requirement has nothing to do with the matching, it's a condition on campaigns only. You'd have to test if this is any better for you:

clicks.stream()

.filter(click -> campaigns.stream()

.filter(camp -> "prospecting".equals(camp.type))

.anyMatch(camp ->

camp.campaignId == click.campaignId &&

camp.end.after(click.date) &&

camp.start.before(click.date)

)

)

.collect(Collectors.toList());

Otherwise, I have never seen a streams solution which does not involve streaming the 2nd collection inside the predicate of the 1st, so you can't do much better than what you did. In terms of readability, if it looks that confusing to you then create a method that test for the boolean condition and call it:

clicks.stream()

.filter(click -> campaigns.stream()

.filter(camp -> "pre".equals(camp.type))

.anyMatch(camp -> accept(camp, click))

)

.collect(Collectors.toList());

static boolean accept(Campaign camp, Click click) {

return camp.campaignId == click.campaignId &&

camp.end.after(click.date) &&

camp.start.before(click.date);

}

Finally, 2 unrelated suggestions:

Don't use the old Date class, instead use the new java.time API's LocalDate.

If Campaign's type can only have some predefined values (like "submitted", "prospecting", "accepted"...) then an enum would be a better fit than a general String.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值