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

  • A+

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 =; -> 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)        .collect(Collectors.groupingBy(            Player::getPoints,            TreeMap::new,            Collectors.toList()        ))        .lastEntry()        .getValue(); 


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