Java8 Map根据key排序和根据value排序

1、根据key排序

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>(3);
    map.put("ccc", "ccc");
    map.put("aaa", "aaa");
    map.put("bbb", "bbb");

    // 注意:这里不能用HashMap存,HashMap的遍历顺序是随机的
    // Collectors.toMap()默认是HashMap
    TreeMap<String, String> result = map.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getKey))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k1, k2) -> k1, TreeMap::new));
    System.out.println("result: " + result);
}

输出结果:

result: {aaa=aaa, bbb=bbb, ccc=ccc}

2、根据value排序

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>(3);
    map.put("ccc", "ccc");
    map.put("aaa", "aaa");
    map.put("bbb", "bbb");

    // 注意:这里不能用HashMap存,HashMap的遍历顺序是随机的
    // Collectors.toMap()默认是HashMap
    TreeMap<String, String> result = map.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getValue))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, TreeMap::new));
    System.out.println("result: " + result);
}

输出结果:

result: {aaa=aaa, bbb=bbb, ccc=ccc}

版权声明:本文为qq_33204709原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。