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()"
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With