Map can't be sorted by value
Map can't be sorted by value , so that we can change map to List and then sort the list .
Collections.sort( List list , Comparator<? super T> c)
In order to keep simple style of coding , we can add the Comparator out ot main class .
class listCompare implements Comparator< Map.Entry<String,Integer> >{
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// Must apply compareTo() functin , to have more security .
return o1.getValue().compareTo(o2.getValue());
}
}
Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class mapSortByValue{
public static void main(String [] args){
// New a Map
Map<String, Integer > map = new TreeMap<String , Integer >();
map.put("A", 4);
map.put("C", 2);
map.put("B", 1);
map.put("D", 3);
// Change Map to List
List<Map.Entry<String,Integer> > list = new ArrayList<Map.Entry<String,Integer> >(map.entrySet());
// Sorting ...
Collections.sort(list, new listCompare());
// print
for(Map.Entry<String ,Integer > one:list){
System.out.println(one.getKey() + ":" + one.getValue() );
}
}
}
class listCompare implements Comparator<Map.Entry<String , Integer > > {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
B:1
C:2
D:3
A:4