java 8 - 打印按键排序的地图

问题描述 投票:1回答:2

我打印一个按键排序的地图,中间对象LinkedHashMap如下;

 LinkedHashMap<String, AtomicInteger> sortedMap = wcMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 sortedMap.forEach((k, v) -> System.out.println(String.format("%s ==>> %d",k, v.get())));

如何在收集之前直接从流中打印出来?

java-8 java-stream
2个回答
4
投票

如果您对收集的LinkedHashMap不感兴趣:

wcMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
        .forEachOrdered(e -> System.out.println(String.format("%s ==>> %d", e.getKey(), e.getValue().get()));

甚至更好:

wcMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
        .map(e -> String.format("%s ==>> %d", e.getKey(), e.getValue().get()))
        .forEachOrdered(System.out::println);

如果您仍然需要生成的LinkedHashMap,请使用peek()

wcMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
        .peek(e -> System.out.println(String.format("%s ==>> %d", e.getKey(), e.getValue().get())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

1
投票

你不能在收集之前使用forEach,因为那会消耗流,这意味着你不能再收集了。

您可以使用peek中间操作来执行某个操作(主要是为了支持调试,您希望在流经管道中的某个点时查看元素),然后使用collectcollect然后应用forEach。完成。

peek的示例:

LinkedHashMap<String, AtomicInteger> sortedMap = wcMap.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .peek(e -> System.out.println(String.format("%s ==>> %d", e.getKey(), e.getValue().get())))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

此外,如果您只对打印数据感兴趣,则无需将结果转储到Map实例中,因为它是不必要的,可以避免。因此,您可以在forEach操作之后链接sorted终端操作并打印数据。

© www.soinside.com 2019 - 2024. All rights reserved.