final Mapmap = new HashMap ();
map.put("语文课本",11);
map.put("英语课本",9);
map.put("数学课本",20);
map.put("政治课本",12);
map.put("化学课本",12);
System.out.println(map.toString());
//结果为{政治课本=12,英语课本=9,数学课本=20,语文课本=11,化学课本=12}
MaporderByValue=new TreeMap (
new Comparator(){
public int compare(String obj1,String obj2){
if(map.get(obj1)!=map.get(obj2)){
return map.get(obj2).compareTo(map.get(obj1));
}else{
return map.get(obj1);
}
}
}
);
orderByValue.putAll(map);
System.out.println(orderByValue.toString());
//结果为{数学课本=20,政治课本=12,化学课本=12,语文课本=11,英语课本=9}
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
public class SortMapByValue {
public static void main(String[] args){
TreeMap
newMap.put("dsaf1", 1);
newMap.put("dsaf9", 9);
newMap.put("dsaf4", 4);
newMap.put("dsaf7", 7);
newMap.put("dsaf6", 6);
newMap.put("dsaf3", 3);
newMap.put("dsaf10", 10);
ByValueComparator bvc =new ByValueComparator(newMap);
List
Collections.sort(newList, bvc);
for(String str:newList){
System.out.println(str+"================================="+newMap.get(str));
}
}
/**
* @description
* 对HashMap按值进行排序
*
* */
static class ByValueComparator implements Comparator
TreeMap
public ByValueComparator(TreeMap
this.base_map = base_map;
}
public int compare(String arg0, String arg1) {
if (!base_map.containsKey(arg0) || !base_map.containsKey(arg1)) {
return 0;
}
if (base_map.get(arg0) < base_map.get(arg1)) {
return 1;
} else if (base_map.get(arg0) == base_map.get(arg1)) {
return 0;
} else {
return -1;
}
}
}
}
这样行吗 你看看