Map根据key或者value排序

1、根据key排序

//输出结果
Map<String,String> result = new HashMap<>(); //输入数据 Map<String,String> map = new HashMap<>(); map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(x->result.put(x.getKey(),x.getValue()));

2、根据value排序

//输出结果
Map<String, Integer> valueResult = new HashMap<>();
//输入数据 Map
<String, Integer> map = new HashMap<>(); map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .forEachOrdered(b->valueResult.put(b.getKey(), b.getValue()));

总经:就是 comparingByValue() 与 comparingByKey()的不同

原文地址:https://www.cnblogs.com/Crysta1/p/13048238.html