0

我有Stream<String>一个文件,现在我想将相等的单词组合成一个Map<String, Integer>重要的,这个单词在Stream<String>.

我知道我必须使用collect(Collectors.groupingBy(..)),但我不知道如何使用它。

如果有人可以提供一些提示如何解决这个问题,那就太好了!

4

1 回答 1

1

Map<String, Long>使用Collectors.counting()as 下游收集器很容易创建:

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)));
于 2015-08-12T04:53:32.503 回答