Java 8 Lambda - 按另一个集合过滤集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26170264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 Lambda - Filter collection by another collection
提问by Shervin Asgari
I have a Set<String> usernames
and List<Player> players
我有一个Set<String> usernames
和List<Player> 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
我知道如何在 Java 8 之前的 Vanilla 中执行此操作
List<Player> distinctPlayers = new ArrayList<Player>();
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
我正在尝试使用 Lambda 表达式编写这个简单的代码,但我正在努力usernames.contains()
在过滤器中工作
players.stream().filter(!usernames.contains(p -> p.getUsername()))
.collect(Collectors.toList());
This doesn't compile. "Cannot resove method getUsername()"
这不编译。“无法解析方法 getUsername()”
回答by Jon Skeet
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?"
你在错误的地方得到了 lambda 表达式 - 整个参数filter
应该是 lambda 表达式。换句话说,“给定一个玩家p
,我应该过滤它还是不过滤它?”
players.stream().filter(p -> !usernames.contains(p.getUsername()))