如何使用Java流获取具有相同最大值的所有对象? [英] How to get all objects having the same max value with Java streams?

查看:172
本文介绍了如何使用Java流获取具有相同最大值的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些得分高手.我想使用流和过滤器让所有共享最大积分的玩家.

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 ?

推荐答案

您可以先收集到TreeMap,仅获取最后一个条目(最大值为

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

这篇关于如何使用Java流获取具有相同最大值的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆