如何从HashMap中获取与最大值对应的Key?

发布于 2025-01-19 04:22:01 字数 425 浏览 2 评论 0 原文

我有以下 treemap 具有给定2个值:

Map<Integer, Integer> map = new TreeMap<>();

// 1 --> 3
// 2 --> 4

我想获得具有最大值的键。我通过以下方式获得最大值:

int max = map.values().stream().max(Integer::compare).get();

// 4

但是,我无法根据此最大值过滤地图键。那么,如何获得最大值(2)的关键?还是 treemap 中给定值的键?我使用 treemap 而不是 hashmap ,以便在需要时可以对地图进行排序(也许不需要)。

I have the following TreeMap with the given 2 values:

Map<Integer, Integer> map = new TreeMap<>();

// 1 --> 3
// 2 --> 4

I want to get the key which has the max value. I get the max value via:

int max = map.values().stream().max(Integer::compare).get();

// 4

However, I cannot filter the map keys based on this max value. So, how can I get the key of the max value (2)? Or key of the given value in TreeMap? I used TreeMap instead of HashMap so that I can sort the map if needed (maybe not need).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

眼眸印温柔 2025-01-26 04:22:01

我使用了TreeMap而不是HashMap,这样我就可以在需要时对地图进行排序(也许不需要)。

为此,HashMap 就足够了,如果您不将其用于其他用途,则可以将 TreeMap 替换为 HashMap。此外,TreeMap 无法帮助完成此任务,因为根据 维护条目的顺序,而不是基于值(您的示例稍微有点误导 - 最大值映射到最大键,如果更改它,TreeMap将不再有帮助)。

要使用 Stream API 解决此问题,首先,您需要在条目集上创建一个流,因为当您只有值时无法访问键。

终端操作 max() 返回一个可选对象,该对象将保存条目(如果结果存在)。在可选对象上调用的方法 map() 会将 Optional> 转换为 Optional

在这种情况下,方法 orElseThrow() 将是 get() 的更好替代方法。如果可选对象为空,两者都会抛出异常。如果根据您的逻辑,保证值存在,那么最好使用 orElseThrow() 显式指定您的意图是在结果不存在时抛出异常,因为这种情况是异常的。

NavigableMap<Integer, Integer> map = new TreeMap<>();

int maxKey = map.entrySet().stream()
        .max(Map.Entry.comparingByValue()) // Optional<Map.Entry<Integer, Integer>> - entry
        .map(Map.Entry::getKey)            // Optional<Integer> - key
        .orElseThrow();

由于多个键可能具有相同的值,因此最大值可能会映射到多个键。在这种情况下,您可能想要获取这些键的列表:

NavigableMap<Integer, Integer> map = new TreeMap<>();

int maxValue = map.entrySet().stream()
        .max(Map.Entry.comparingByValue())
        .map(Map.Entry::getValue)
        .orElseThrow();    
    
List<Integer> maxValues = map.entrySet().stream()
        .filter(entry -> entry.getValue() == maxValue)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Sidenote:当您使用 TreeMap 并且不希望为该变量分配未排序的值时实现接口 Map,然后使用接口 NavigableMap 作为类型。它将为您提供对 getFirstEntry()getFirstKey()higherEntry() 等不可用的方法的访问与地图

I used TreeMap instead of HashMap so that I can sort the map if needed (maybe not need).

For that purpose, HashMap will suffice, you might replace TreeMap with a HashMap if you are not utilizing it for anything else. And moreover, TreeMap can't help with this task because maintains the order of entries based on keys, not on values (your example is slightly misleading - max value is mapped to a max key, if you change it, TreeMap will no longer be helpful).

To solve this problem with Stream API, firstly, you need to create a stream over the entry set, because you can't access a key when you have only a value.

Terminal operation max() returns an optional object that will hold entry (if result is present). Method map() invoked on an optional will transform Optional<Map.Entry<Integer, Integer>> into Optional<Integer>.

Method orElseThrow() in this case will be a better alternative to get(). Both will throw an exception if optional object will be empty. If according to your logic, value is guaranteed to be present it better specify explicitly with orElseThrow() that your intention is to throw an exception when result is not present, because this case is abnormal.

NavigableMap<Integer, Integer> map = new TreeMap<>();

int maxKey = map.entrySet().stream()
        .max(Map.Entry.comparingByValue()) // Optional<Map.Entry<Integer, Integer>> - entry
        .map(Map.Entry::getKey)            // Optional<Integer> - key
        .orElseThrow();

Since multiple keys could have the same value, it is possible that max value will be mapped to more than one key. In this case you might want to get a list of these keys:

NavigableMap<Integer, Integer> map = new TreeMap<>();

int maxValue = map.entrySet().stream()
        .max(Map.Entry.comparingByValue())
        .map(Map.Entry::getValue)
        .orElseThrow();    
    
List<Integer> maxValues = map.entrySet().stream()
        .filter(entry -> entry.getValue() == maxValue)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

Sidenote: when you are working with a TreeMap and don't expect that variable could be assigned with an unsorted implementation of the interface Map, then use interface NavigableMap as a type. It'll provide you access to such methods as getFirstEntry(), getFirstKey(), higherEntry(), etc. that will not be available with Map.

随风而去 2025-01-26 04:22:01

要获得正确的密钥,您可以使用以下命令:

Optional<Map.Entry<Integer,Integer>> entry = map.entrySet().stream().max(Map.Entry.comparingByValue());
System.out.println(entry.get().getKey());

To get the proper key you can use this:

Optional<Map.Entry<Integer,Integer>> entry = map.entrySet().stream().max(Map.Entry.comparingByValue());
System.out.println(entry.get().getKey());
别挽留 2025-01-26 04:22:01

如果使用适当的接口,这将非常容易。

NavigableMap<Integer, Integer> map = new TreeMap<>();
return map.lastEntry().getKey();

更重要的是,这比使用任何流都要高得多。

If you use the proper interface, this is extremely easy.

NavigableMap<Integer, Integer> map = new TreeMap<>();
return map.lastEntry().getKey();

More importantly, this is much more efficient than using any Stream at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文