标签:map排序
1、按键排序
使用treemap按照键来排序
@Test
public void treeMap(){
//传入的比较器只能根据key来排序,TreeMap如不指定排序器,默认将按照key值进行升序排序
//指定排序器按照key值降序排列 ,
//Comparator中泛型必须传入key类型的的超类TreeMap(Comparator<? super K> comparator)
TreeMap<String, Integer> treeMap=new TreeMap<String, Integer>(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return o2.hashCode()-(o1.hashCode());
//如果key是String类型 return o2.compareTo(o1);
}
}) ;
treeMap.put("2", 1);
treeMap.put("b", 1);
treeMap.put("1", 1);
treeMap.put("a", 1);
System.out.println("treeMap="+treeMap);
}2、按值排序
/**
* @see map排序
* @param oriMap
* @return
*/
public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) {
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
if (oriMap != null && !oriMap.isEmpty()) {
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(oriMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
Map.Entry<String, Integer> tmpEntry = null;
while (iter.hasNext()) {
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
}
return sortedMap;
}本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1763107
标签:map排序
原文地址:http://tianxingzhe.blog.51cto.com/3390077/1763107