[英]Stream<String> to Map<String, Integer>
我有一个文件的Stream<String>
,现在我想将相等的单词组合到Map<String, Integer>
中,该单词计数在Stream<String>
该单词的频率。
我知道我必须使用collect(Collectors.groupingBy(..))
,但是我不知道如何使用它。
如果有人可以提供一些解决该问题的提示,那就太好了!
使用Collectors.counting()
作为下游收集器来创建Map<String, Long>
很容易:
Stream<String> s = Stream.of("aaa", "bb", "cc", "aaa", "dd");
Map<String, Long> map = s.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()));
如果您不喜欢Long
类型,可以通过以下方式算入Integer
:
Map<String, Integer> mapInt = s.collect(Collectors.groupingBy(
Function.identity(),
Collectors.reducing(0, str -> 1, Integer::sum)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.