0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

3 Answers3

6

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());
    }
};
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
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...

geenux
  • 297
  • 4
  • 15
1

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

Community
  • 1
  • 1
Charles Menguy
  • 40,830
  • 17
  • 95
  • 117