Java sorting and HashMap

2019-08-27 11:34发布

问题:

I have a HashMap<String, Integer> How can I sort this data structure and keep the key-value mappings? I want to sort by VALUES not keys.

Collection<Integer> counts = tableFrequency.values();

But then I lose the key mappings. Or is there a better associative data-structure that I could have used instead of the HashMap?

回答1:

To sort a Map by its values, you could grab its entrySet and sort that with a custom Comparator.

List<Entry<K,V>> sorted = new ArrayList<>(map.entrySet());
Collections.sort(sorted, new Comparator<Entry<K,V>>() {
    public int compare(Entry<K,V> o1, Entry<K,V> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
};


回答2:

TreeMap keeps the elements in the order in wich you added them. It seems like a perfect answer for you.

Beware though, some actions will be way slower than with a HashMap, things such as searching...



回答3:

The class TreeMap is what you want:

TreeMap treeMap = new TreeMap();

treeMap.put("One", new Integer(1));
treeMap.put("Two", new Integer(2));

Object obj = treeMap.get("Two");
System.out.println(obj);

It uses the compare() method to be able to sort elements.

Since your new question is about sorting by values, this is a duplicate of this post