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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

What happens with this approach if multiple keys have the same value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.