Sort Map based on the values in java

Sort Map based on the values in java, so using HashMap we can store the values, then swap the values key as value and value as key and create another Map of TreeMap this will sort based on the key, So in previous HasMap values are became key in new TreeMap and those are sorted now.

Now take a LinkedHashMap this will store the values in order, so at end we will get sorted Map based on the values.


import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapReverseBasedOnValue {

public static void main(String[] args) {

Map <Integer, String> map = new HashMap();
map.put(1, "User6");
map.put(2, "User1");
map.put(3, "User4");
map.put(4, "User9");
map.put(5, "User5");

Map<String , Integer> temp = new TreeMap();

Map<Integer, String> sortedMap = new LinkedHashMap();

for(Map.Entry<Integer, String> mp : map.entrySet()){
temp.put(mp.getValue(), mp.getKey());
}
for(Map.Entry<String, Integer> mp : temp.entrySet()){
sortedMap.put(mp.getValue(), mp.getKey());
}

System.out.println(map);
System.out.println(temp);
System.out.println(sortedMap);
}
}

Post a Comment

Previous Post Next Post