Coding Gems – Gem #1 – Java Sort Map by Value
package com.wordpress.Oxcafebabe.gems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
*
* @author mahdeto
*
*/
public class SortByValueMaps {
public static void main(String[] args) {
Map<String, Integer> test = new HashMap<String, Integer>(3);
test.put("someValue", 1);
test.put("aKeyThatNormallyComesBefore", 3);
test.put("someOtherValue", 2);
System.out.println(sortMapByValues(test));
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValues(Map<K, V> sortMe) {
List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(sortMe.size());
entries.addAll(sortMe.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map<K, V> sortedMap = new LinkedHashMap<K, V>(sortMe.size());
for(Map.Entry<K, V> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
This outputs:
{someValue=1, someOtherValue=2, aKeyThatNormallyComesBefore=3}
Advertisement

Enta bethazar sa7?
this is what you did out of boredom?
Yes Ma’am
println(
Map(“someValue” → 1, “aKeyThatNormallyComesBefore” → 3, “someOtherValue” → 2).toList.sortBy(_._2).toMap) // hehehe
Shereer