简体   繁体   English

使用Java8从对象值映射中获取最大值键

[英]Get Maximum valued key from a Map of object values using Java8

I have a below map with Integer as key and Entity object as values as below 我有一个下面的地图,其中Integer作为键,而Entity对象作为值,如下所示

Map<Integer, Entity> skuMap;

Entity.java:

private StatisticsEntity statistics;

StatisticsEntity.java:

private Integer count;

I want to get the key where the maximum count of StatisticsEntity from the skuMap. 我想从skuMap中获取最大的StatisticsEntity计数。

I got the result with below codesnippet of Java8 我得到了下面的Java8代码片段的结果

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

But I want to refactor the above with Comparator.comparingInt , any help would be appreciated. 但是我想用Comparator.comparingInt重构上述内容,任何帮助将不胜感激。

Optional<Integer> sku = skuMap.entrySet().stream()
    .max(
        Comparator.comparingInt(
            entry -> entry.getValue().getStatistics().getCount()
        )
    )
    .map(Map.Entry::getKey);

I would've prefer one of those 2 approaches to avoid NullPointerException(in case of empty map or no statistics): 我宁愿使用这两种方法中的一种来避免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);

If you prefer with Comparator.comparingInt , it have a ToIntFunction as parameter. 如果您更喜欢Comparator.comparingInt ,则可以使用ToIntFunction作为参数。 Input is the element you want to compare and output should be an integer - in your case count. 输入是要比较的元素,输出应为整数-以您的情况为单位。 Behind the scene,it will return exactly what you've written above (s1, s2) -> Integer.compare(s1.getValue().getStatistics().getCount(), s2.getValue().getStatistics().getCount()) : 在幕后,它将完全返回您上面写的内容(s1, s2) -> Integer.compare(s1.getValue().getStatistics().getCount(), s2.getValue().getStatistics().getCount())

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

Also I think all IDE suggest the replacement. 我也认为所有IDE都建议更换。 In IntelliJ, I've just press Alt+Enter on your version and it suggests me the replacement with Comparator.comparingInt . 在IntelliJ中,我只需在您的版本上按Alt + Enter,它建议我用Comparator.comparingInt替代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM