How to get all objects having the same max value with Java streams?

  • A+
Category:Languages

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: