4
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

Paul Bellora
  • 53,024
  • 17
  • 128
  • 180
ealeon
  • 11,288
  • 20
  • 84
  • 159
  • 4
    possible duplicate of [How to sort a Map on the values in Java?](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java) (beware of the top-voted answer) – Paul Bellora Dec 02 '12 at 23:01

2 Answers2

2

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.

Isaac
  • 16,118
  • 5
  • 56
  • 81
amit
  • 172,148
  • 26
  • 225
  • 324
1

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

Amir Pashazadeh
  • 6,884
  • 3
  • 36
  • 66