Reputation: 12452
private Map<Character, Integer> frequencies;
I have a Map
with Character
being Key and its associated Integer
being Value.
Whats the best/fastest/efficeint way to sort by Value?
i.e Map may have
a,1
c,10
p,5
s,7
and after sorted,
it would be
a,1
p,5
s,7
c,10
I was thinking about doing it with Priority Queue and with integer but i would lose the Character value if the integer vals are duplicates
Upvotes: 4
Views: 2069
Reputation: 178451
A priority queue is a decent approach - all you need to do is get the Entry
set from the map, and override a Comparator
as the input 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());
}
Will yield (as expected):
a=1
p=5
2=7
c=10
Note: Avoid using a Set
or a Map
with keys as the values of the map - because it will NOT handle duplicate values well.
Upvotes: 2
Reputation: 7302
Use Google Guava. It contains BiMap implementations which can be inversed, and then just sort on inversed 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 iterate the sortedInversed
Upvotes: 1