Java8 对 Map 排序

Java基础

浏览数:99

2019-9-7

AD:资源代下载服务

引言

使用 keys 或 values 对 map 排序。

1. 快速开始

步骤:

  1. 将 map 转为流
  2. 对流排序
  3. 收集并返回一个新的 LinkedHashMap (保持顺序)
Map result = map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())             
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

默认情况下,Collectors.toMap 将返回一个 HashMap。

2. 按 Keys 排序

public static void main(String[] args) {
    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    unsortMap.put("c", 20);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("y", 8);
    unsortMap.put("n", 99);
    unsortMap.put("g", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    System.out.println("Original...");
    System.out.println(unsortMap);

    // sort by keys, a,b,c..., and return a new LinkedHashMap
    // toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
    LinkedHashMap<String, Integer> result = unsortMap.entrySet().stream()
        .sorted(Entry.comparingByKey()).collect(Collectors
            .toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> oldValue,
                LinkedHashMap::new));

    // 不推荐,但是很有效。

    Map<String, Integer> result2 = new LinkedHashMap<>();
    unsortMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x->result2.put(x.getKey(),x.getValue()));

    System.out.println("Sorted...");
    System.out.println(result);
    System.out.println(result2);
  }

输出:

Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}

3. 按 Values 排序

public static void main(String[] args) {
    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    unsortMap.put("c", 20);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("y", 8);
    unsortMap.put("n", 99);
    unsortMap.put("g", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    System.out.println("Original...");
    System.out.println(unsortMap);

    //sort by values, and reserve it, 10,9,8,7,6...
    LinkedHashMap<String, Integer> result = unsortMap.entrySet().stream()
        .sorted(Entry.comparingByValue(Comparator.reverseOrder()))
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> oldValue,
                LinkedHashMap::new));

    // 替代方式
    Map<String, Integer> result2 = new LinkedHashMap<>();
    unsortMap.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

    System.out.println("Sorted...");
    System.out.println(result);
    System.out.println(result2);
  }

输出:

Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}
Sorted...
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}

4. Map<Object,Object>

Stream 不能直接对 Map<Object,Object> 进行排序,可以现将它转为 Map<String,String>,再操作:

public static void main(String[] args) {
    Properties properties = System.getProperties();
    Set<Entry<Object, Object>> entries = properties.entrySet();

    LinkedHashMap<String, String> collect = entries.stream()
        .collect(Collectors.toMap(k -> (String) k.getKey(), e -> (String) e.getValue()))
        .entrySet()
        .stream().sorted(Entry.comparingByKey())
        .collect(Collectors
            .toMap(Entry::getKey, Entry::getValue, (oldValue, newValue) -> oldValue,
                LinkedHashMap::new));

    collect.forEach((k,v)->System.out.println(k + ":" + v));
  }

输出:

awt.toolkit:sun.lwawt.macosx.LWCToolkit
file.encoding:UTF-8
file.encoding.pkg:sun.io
file.separator:/
ftp.nonProxyHosts:local|*.local|169.254/16|*.169.254/16
gopherProxySet:false
http.nonProxyHosts:local|*.local|169.254/16|*.169.254/16
java.awt.graphicsenv:sun.awt.CGraphicsEnvironment
java.awt.printerjob:sun.lwawt.macosx.CPrinterJob

.....
sun.boot.library.path:/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib
sun.cpu.endian:little
sun.cpu.isalist:
sun.io.unicode.encoding:UnicodeBig
sun.java.command:com.jimzhang.map.sort.ObjectTest
sun.java.launcher:SUN_STANDARD
sun.jnu.encoding:UTF-8
sun.management.compiler:HotSpot 64-Bit Tiered Compilers
sun.os.patch.level:unknown
user.country:CN
user.dir:/Users/zhangjinmiao/Documents/GitHub/java-8-demo
user.home:/Users/zhangjinmiao
user.language:zh
user.name:zhangjinmiao
user.timezone:

源码见:
java-8-demo

系列文章详见:Java 8 教程

作者:山川尽美