dw做的网站怎么发布,网上做调查网站,福州做网站的公司,潍坊住房公积金官网登录Map排序的方式有很多种#xff0c;这里记录下自己总结的两种比较常用的方式#xff1a;按键排序(sort by key)#xff0c; 按值排序(sort by value)。
1、按键排序
jdk内置的java.util包下的TreeMapK,V既可满足此类需求#xff0c;向其构造方法TreeMap(Comparato…Map排序的方式有很多种这里记录下自己总结的两种比较常用的方式按键排序(sort by key) 按值排序(sort by value)。
1、按键排序
jdk内置的java.util包下的TreeMapK,V既可满足此类需求向其构造方法TreeMap(Comparator super K comparator) 传入我们自定义的比较器即可实现按键排序。
实现代码
public class MapSortDemo {public static void main(String[] args) {MapString, String map new TreeMapString, String();map.put(KFC, kfc);map.put(WNBA, wnba);map.put(NBA, nba);map.put(CBA, cba);MapString, String resultMap sortMapByKey(map); //按Key进行排序for (Map.EntryString, String entry : resultMap.entrySet()) {System.out.println(entry.getKey() entry.getValue());}}/*** 使用 Map按key进行排序* param map* return*/public static MapString, String sortMapByKey(MapString, String map) {if (map null || map.isEmpty()) {return null;}MapString, String sortMap new TreeMapString, String(new MapKeyComparator());sortMap.putAll(map);return sortMap;}
}比较器类
class MapKeyComparator implements ComparatorString{Overridepublic int compare(String str1, String str2) {return str1.compareTo(str2);}
}2、按值排序
按值排序就相对麻烦些了貌似没有直接可用的数据结构能处理类似需求需要我们自己转换一下。 Map本身按值排序是很有意义的很多场合下都会遇到类似需求可以认为其值是定义的某种规则或者权重。
原理将待排序Map中的所有元素置于一个列表中接着使用Collections的一个静态方法 sort(List list, Comparator super T c) 来排序列表同样是用比较器定义比较规则。排序后的列表中的元素再依次装入Map为了肯定的保证Map中元素与排序后的List中的元素的顺序一致使用了LinkedHashMap数据类型。
实现代码
public class MapSortDemo {public static void main(String[] args) {MapString, String map new TreeMapString, String();map.put(KFC, kfc);map.put(WNBA, wnba);map.put(NBA, nba);map.put(CBA, cba);MapString, String resultMap sortMapByKey(map); //按Key进行排序
// MapString, String resultMap sortMapByValue(map); //按Value进行排序for (Map.EntryString, String entry : resultMap.entrySet()) {System.out.println(entry.getKey() entry.getValue());}}/*** 使用 Map按value进行排序* param map* return*/public static MapString, String sortMapByValue(MapString, String oriMap) {if (oriMap null || oriMap.isEmpty()) {return null;}MapString, String sortedMap new LinkedHashMapString, String();ListMap.EntryString, String entryList new ArrayListMap.EntryString, String(oriMap.entrySet());Collections.sort(entryList, new MapValueComparator());IteratorMap.EntryString, String iter entryList.iterator();Map.EntryString, String tmpEntry null;while (iter.hasNext()) {tmpEntry iter.next();sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());}return sortedMap;}
}比较器类
class MapValueComparator implements ComparatorMap.EntryString, String {Overridepublic int compare(EntryString, String me1, EntryString, String me2) {return me1.getValue().compareTo(me2.getValue());}
}