首页 > 解决方案 > 使用Java8从对象值映射中获取最大值键

问题描述

我有一个下面的地图,其中整数作为键,实体对象作为值,如下所示

Map<Integer, Entity> skuMap;

Entity.java:

private StatisticsEntity statistics;

StatisticsEntity.java:

private Integer count;

我想从 skuMap 中获取 StatisticsEntity 的最大计数所在的键。

我用下面的 Java8 代码片段得到了结果

Integer sku = skuMap.entrySet().stream().max((s1, s2) -> Integer.compare(s1.getValue().getStatistics().getCount(), s2.getValue().getStatistics().getCount())).orElse(null).getKey();

但我想用 重构上述内容Comparator.comparingInt,任何帮助将不胜感激。

标签: javajava-8comparator

解决方案


我更喜欢这两种方法中的一种来避免 NullPointerException(在空地图或没有统计信息的情况下):

int max =  skuMap.values().stream().mapToInt(e -> e.getStatistics().getCount()).max().orElse(0);


Integer max2 = skuMap.values().stream().map(e -> e.getStatistics().getCount()).max(Integer::compareTo).orElse(null);

如果你喜欢 with Comparator.comparingInt,它有一个ToIntFunctionas 参数。输入是您要比较的元素,输出应该是一个整数 - 在您的情况下计数。在幕后,它将完全返回您上面写的内容(s1, s2) -> Integer.compare(s1.getValue().getStatistics().getCount(), s2.getValue().getStatistics().getCount())

Comparator.comparingInt(entry -> entry.getValue().getStatistics().getCount())

另外我认为所有 IDE 都建议更换。在 IntelliJ 中,我刚刚在您的版本上按 Alt+Enter,它建议我用 Comparator.comparingInt.


推荐阅读