java 集合过滤,Java 8 Lambda - 由另一个集合过滤集合

I have a Set usernames

and List players

I would like to filter out those players that are not in the Set.

I know how to do this in Vanilla pre Java 8

List distinctPlayers = new ArrayList();

for(Player p : players) {

if(!usernames.contains(p.getUsername()) distinctPlayers.add(p);

}

I am trying to write this simple code with a Lambda expression, but I am struggling to get usernames.contains() to work in a filter

players.stream().filter(!usernames.contains(p -> p.getUsername()))

.collect(Collectors.toList());

This doesn't compile. "Cannot resove method getUsername()"

解决方案

You've got the lambda expression in the wrong place - the whole of the argument to filter should be the lambda expression. In other words, "Given a player p, should I filter it or not?"

players.stream().filter(p -> !usernames.contains(p.getUsername()))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值