Shervin Asgari
Shervin Asgari

Reputation: 24499

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

Upvotes: 17

Views: 23720

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

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

Upvotes: 36

Related Questions