I have players which have points. I want to get all the players who share the max amount of points using a stream and a filter.
public class Player {
private int points; // Getter omitted
}
I can do this by first getting the player with the most points, and the filtering all players that have the same amount.
Player topPlayer = players.stream().max(Comparator.comparing(Player::getPoints)).orElse(null);
players.stream().filter(p -> p.getPoints() == topPlayer.getPoints()).collect(Collectors.toList());
Can this be done with a single predicate / single line ?
解决方案
You could collect to a TreeMap first and only get the last entry (where the max is)
players.stream()
.collect(Collectors.groupingBy(
Player::getPoints,
TreeMap::new,
Collectors.toList()
))
.lastEntry()
.getValue();