如果您不能使用 TreeMap
,在 Java 8 中我们可以使用 Collectors
中的toMap() 方法,该方法接受以下参数:
- keymapper: 用于生成键的映射函数
- valuemapper: 用于生成值的映射函数
- mergeFunction: 合并函数,用于解决与同一键相关联的值之间的冲突
- mapSupplier: 返回一个新的、空的 Map,用于插入结果的函数。
Java 8 示例
Map<String, String> sample = new HashMap<>();
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
Map<String, String> newMapSortedByValue = sample.entrySet().stream()
.sorted(Map.Entry.<String, String>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
我们可以修改示例以使用自定义比较器并基于键进行排序,如下所示:
我们可以修改示例以使用自定义比较器并基于键进行排序,如下所示:
Map<String, String> newMapSortedByKey = sample.entrySet().stream()
.sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));