1.升序排序(TreeMap(默认是升序排列的))
Map<String, Integer> map = new HashMap<>();
// 使用Stream API对Map进行升序排序
Map<String, Integer> sortedMap = new LinkedHashMap<>();
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
2.降序排列
public Map<Integer, Integer> descSortMap(Map<Integer, Integer> nowMap) {
List<Map.Entry<Integer, Integer>> list = new ArrayList(nowMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>(){
public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
return b.getValue() - a.getValue();
}
});
// 只有 LinkedHashMap在存储时会按照写入的顺序来
Map<Integer, Integer> resMap = new LinkedHashMap<>();
for(Map.Entry<Integer, Integer> item : list){
//System.out.println("entry: " + item);
resMap.put(item.getKey(), item.getValue());
}
return resMap;
}