import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Tri {
public static void main(String[] args) {
HashMapmap = new HashMap ();
Comparator comp = new Comparator(map);
TreeMapmap_apres = new TreeMap (comp);
map.put("A",49);
map.put("B",18);
map.put("C",92);
map.put("D",37);
map.put("E",62);
System.out.println("Before sorting: "+map);
map_apres.putAll(map);
System.out.println("After sorting: "+map_apres);
}
}
class Comparator implements Comparator{
Maptuple;
public Comparator(HashMapmap) {
this.tuple = map;
}
//this comparator orders the elements in descending order
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (int) tuple.get(o1) >= (int) tuple.get(o2)) {
return -1;
} else {
return 1;
}
}
}
public static void main(String[] args) {Run:
HashMapmap = new HashMap ();
map.put("A",18.5);
map.put("E",76.8);
map.put("C",24.1);
map.put("F",86.2);
map.put("D",5.7);
map.put("B",84.6);
System.out.println("Before sorting: "+map);
System.out.println("After sorting: "+sortWithValue(map));
}
public static HashMap< String, Double> sortWithValue( HashMap< String, Double> map ){
List< Map.Entry< String, Double> > list =
new LinkedList< Map.Entry< String, Double> > ( map.entrySet() );
Collections.sort( list, new Comparator< Map.Entry< String, Double> > (){
public int compare( Map.Entry< String, Double> o1, Map.Entry< String, Double> o2 ){
return (o1.getValue()).compareTo( o2.getValue());
}
});
HashMap< String, Double> map_apres = new LinkedHashMap< String, Double> ();
for(Map.Entry< String, Double> entry : list)
map_apres.put( entry.getKey(), entry.getValue() );
return map_apres;
}
Before sorting: {D=5.7, E=76.8, F=86.2, A=18.5, B=84.6, C=24.1}To sort in descending direction, simply change the order of the comparison in the compare:
After sorting: {D=5.7, A=18.5, C=24.1, E=76.8, B=84.6, F=86.2}
References:return(o2.getValue()).compareTo( o1.getValue());
Please disable your ad blocker and refresh the window to use this website.