Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda - Filter collection by another collection

I have a Set<String> usernames and 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

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

players.stream().filter(!usernames.contains(p -> p.getUsername()))
.collect(Collectors.toList());

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

like image 555
Shervin Asgari Avatar asked Oct 02 '14 21:10

Shervin Asgari


1 Answers

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()))
like image 188
Jon Skeet Avatar answered Nov 16 '22 00:11

Jon Skeet