java - 使用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
,任何帮助将不胜感激。
解决方案
我更喜欢这两种方法中的一种来避免 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
,它有一个ToIntFunction
as 参数。输入是您要比较的元素,输出应该是一个整数 - 在您的情况下计数。在幕后,它将完全返回您上面写的内容(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
.
推荐阅读
- reactjs - 是否有特定于 React 的 Typescript 类型列表?
- sql-server - 从 SQL Server 2016+ 加入 XML 列
- angular - 即使在设置 CORS 后,请求的资源上也没有“Access-Control-Allow-Origin”标头
- javascript - 是否可以在没有用户提供凭据的情况下在后端验证用户?
- typescript - TypeError:table.rows 不是函数 - 在量角器中从特征文件访问示例时
- c# - 如何在项目 B 中使用项目 A 的 UserManager?
- python - 如何在 GSuite 中设置有关帐户更改活动的警报?
- django - Django-Rest-Framework:没有属性 HelloViewSet
- integration-testing - How to add HTTP header to MicroShedTest and SharedContainerConfig JUnit tests
- rust - 不能将 `hsets` 借为可变的,因为它也被借为不可变的