Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

Sorting Descending order: Java Map

What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but missing a small thing.

Link1: Sorting Map

But the issue I am running into is that by default this is sorted by ascending order by value. I want to order it by descending order:

So what I did was I created a class that implements a comparator

class MyComparator implements Comparator {
    Map map;
    public MyComparator(Map map) {
        this.map = map;
    }
    public int compare(Object o1, Object o2) {
        return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
    }
}

And then I pass my map to the treemap,

MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);

This seems like bad approach because I feel this is inefficient. Is there a way to change the solution in the link to do ordering on descending order by default.

question from:https://stackoverflow.com/questions/18923167/sorting-descending-order-java-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use new TreeMap<>(Collections.reverseOrder());.

Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);

or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator). It works like your approach swapping the two objects before invoking compare/compareTo.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...