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

一、根據key排序java

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()));


二、根據value排序code

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()));
相關文章
相關標籤/搜索