Java 8 Lambda - 由另一个集合过滤集合 [英] Java 8 Lambda - Filter collection by another collection

查看:848
本文介绍了Java 8 Lambda - 由另一个集合过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Set< String>用户名
列表< Player>玩家

我想过滤掉那些不属于套装的玩家。

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

我知道如何在Vanilla pre Java 8中执行此操作

I know how to do this in Vanilla pre Java 8

List<Player> distinctPlayers = new ArrayList<Player>();

for(Player p : players) {
    if(!usernames.contains(p.getUsername()) distinctPlayers.add(p);
} 

我试图用Lambda表达式编写这个简单的代码,但我很难得到 usernames .contains()在过滤器中工作

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());

这不能编译。无法恢复方法getUsername()

推荐答案

你的lambda表达式位于错误的位置 - filter 的整个参数应该是lambda表达式。换句话说,给定一个玩家 p ,我应该过滤它吗?

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()))

这篇关于Java 8 Lambda - 由另一个集合过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆