package day1;
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<String,Integer> newMap=new TreeMap<String,Integer>();
newMap.put("aaa10", 1);
newMap.put("aaa9", 9);
newMap.put("aaa4", 4);
newMap.put("aaa7", 7);
newMap.put("aaa6", 6);
newMap.put("aaa3", 3);
newMap.put("aaa10", 10);
ByValueComparator bvc =new ByValueComparator(newMap);
List<String> newList=new ArrayList<String>(newMap.keySet());
Collections.sort(newList, bvc);
for(String str:newList){
System.out.println(str+".........................."+newMap.get(str));
}
}
/**
* @description
* 对Map按值进行排序
*
* */
static class ByValueComparator implements Comparator<String> {
TreeMap<String, Integer> base_map;
public ByValueComparator(TreeMap<String, Integer> base_map) {
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;
}
}
}
}
那就这个,哥们,你看这是你想要的了吧。也是自定义的比较器。 |