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;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。