我打印一个按键排序的地图,中间对象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())));
如何在收集之前直接从流中打印出来?
如果您对收集的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));
你不能在收集之前使用forEach
,因为那会消耗流,这意味着你不能再收集了。
您可以使用peek
中间操作来执行某个操作(主要是为了支持调试,您希望在流经管道中的某个点时查看元素),然后使用collect
或collect
然后应用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
终端操作并打印数据。