Java Map sort by value

拥有回忆 提交于 2019-11-29 06:41:33

In your compare function, when the values are equal, you should then compare the keys. This will ensure that different keys having the same value will not be "merged", because it disambiguates entries that would otherwise compare equal.

For example:

    @Override
    public int compare(String a, String b) {
        Integer x = base.get(a);
        Integer y = base.get(b);
        if (x.equals(y)) {
            return a.compareTo(b);
        }
        return x.compareTo(y);
    }

(you'll need to modify the code above to match your policy for null values)

Note that your approach of sorting on values is pretty fragile, though. Your "sorted" map will not support addition of new entries, which could be pretty confusing.

base.get(a) ==  base.get(b)

This code compares boxed Integers by reference.

Change it to base.get(a).equals(base.get(b)) and it should work.

Try this ...

HashMap<String, Integer> h = new HashMap<String, Integer>();
h.put("z",30);
h.put("e",10);
h.put("b",20);
h.put("c",20);
List<Map.Entry> a = new ArrayList<Map.Entry>(h.entrySet());
Collections.sort(a,
         new Comparator() {
             public int compare(Object o1, Object o2) {
                 Map.Entry e1 = (Map.Entry) o1;
                 Map.Entry e2 = (Map.Entry) o2;
                 return ((Comparable) e1.getValue()).compareTo(e2.getValue());
             }
         });

for (Map.Entry e : a) {
        System.out.println(e.getKey() + " " + e.getValue());
}

Ouptut:

e 10
b 20
c 20
z 30

Try this:

return base.get(a).compareTo(base.get(b));

To demonstrate that you are incorrect about auto-unboxing:

Integer a = new Integer(2);
Integer b = new Integer(2);
boolean isEqual = ( a == b );
System.out.println("equal: " + isEqual);
System.out.println("a: " + a);
System.out.println("b: " + b);

My output is:

equal: false
a: 2
b: 2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!