Best way to sort map with values

private Map<Character, Integer> frequencies; 

I have a Map , and Character is the key, and its associated Integer is the value.

What is the best / fastest / most efficient way to sort by value?

ie Card may have a, 1
s, 10
p, 5
s, 7
and after sorting, that would be a, 1
p, 5
s, 7
s, 10

I was thinking about doing this with Priority Queue and with an integer, but I would lose the Character value if the integer vals are duplicates

+4
source share
2 answers

The priority queue is a decent approach - all you have to do is get the Entry set from the map and redefine Comparator as the entry to the queue.

 Map<Character,Integer> map = new HashMap<Character, Integer>(); map.put('a',1); map.put('c',10); map.put('p',5); map.put('2',7); PriorityQueue<Entry<Character, Integer>> pq = new PriorityQueue<Map.Entry<Character,Integer>>(map.size(), new Comparator<Entry<Character, Integer>>() { @Override public int compare(Entry<Character, Integer> arg0, Entry<Character, Integer> arg1) { return arg0.getValue().compareTo(arg1.getValue()); } }); pq.addAll(map.entrySet()); while (!pq.isEmpty()) { System.out.println(pq.poll()); } 

Lose (as expected):

 a=1 p=5 2=7 c=10 

Note. Avoid using Set or Map with keys as map values ​​- because it will NOT handle duplicate values.

+2
source

Use Google Guava. It contains BiMap implementations that can be inverted and then simply sorted by the programmed map keys.

 Map<Character, Integer> myMap = HashBiMap.create(); // put your values in myMap Map<Integer, Character> inversed = myMap.inverse(); SortedMap<Integer, Character> sortedInversed = new TreeMap<Integer, Character>(inversed); 

so just repeat the sorting in reverse

+1
source

All Articles