java8 map根据key排序和根据value排序

深渊向深渊呼唤

1、根据key排序

Map<String,String> result = new LinkedHashMap<>();
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 LinkedHashMap<>();
Map<String, Integer> map = new HashMap<>();
map.entrySet().stream()
    .sorted(Map.Entry
        .comparingByValue())
        .forEachOrdered(b->valueResult.put(b.getKey(), b.getValue()));

 

栏目