Java – how to sort HashMap entries by comparing values, where each value is int []?

I have a HashMap defined as HashMap < string, int [] > The value is int [], where there are only 2 numbers What I want to do is sort the entries of this HashMap by the sum of these two numbers

This is what I have I'm using java 8 I just need to add the part where I sum 2 integers in int [], treat it as a number, and then sort it in the following way, but I'm not sure how to add this part

hm.entrySet().stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverSEOrder()))

Solution

This is the solution of Java 8 comparator Lambdas:

map.entrySet().stream()
              .sorted(Map.Entry.comparingByValue(
                      (v1,v2) -> v2[0] + v2[1] - v1[0] - v1[1]));

Please note that this solution has the risk of overflow / underflow. Please refer to leeyuiwah answer for a better solution The idea is to use the comparisonlong method instead

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>