map的排序总结
1、按键排序
使用treemap按照键来排序
@TestpublicvoidtreeMap(){//传入的比较器只能根据key来排序,TreeMap如不指定排序器,默认将按照key值进行升序排序//指定排序器按照key值降序排列,//Comparator中泛型必须传入key类型的的超类TreeMap(Comparator<?superK>comparator)TreeMap<String,Integer>treeMap=newTreeMap<String,Integer>(newComparator<Object>(){@Overridepublicintcompare(Objecto1,Objecto2){returno2.hashCode()-(o1.hashCode());//如果key是String类型returno2.compareTo(o1);}});treeMap.put("2",1);treeMap.put("b",1);treeMap.put("1",1);treeMap.put("a",1);System.out.println("treeMap="+treeMap);}
2、按值排序
/***@seemap排序*@paramoriMap*@return*/publicstaticMap<String,Integer>sortMapByValue(Map<String,Integer>oriMap){Map<String,Integer>sortedMap=newLinkedHashMap<String,Integer>();if(oriMap!=null&&!oriMap.isEmpty()){List<Map.Entry<String,Integer>>entryList=newArrayList<Map.Entry<String,Integer>>(oriMap.entrySet());Collections.sort(entryList,newComparator<Map.Entry<String,Integer>>(){@Overridepublicintcompare(Entry<String,Integer>o1,Entry<String,Integer>o2){returno2.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());}}returnsortedMap;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。