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
  • 54,340
  • 18
  • 130
  • 181
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • 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,458
  • 5
  • 57
  • 81
amit
  • 175,853
  • 27
  • 231
  • 333
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
  • 7,170
  • 3
  • 39
  • 69