2015-04-29 58 views
0

我有一個Stream<String>的文件,現在我想將相等的單詞組合成一個Map<String, Integer>這個計數,這個單詞在Stream<String>中的頻率。流<String>到地圖<字符串,整數>

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

這將是非常好的,如果有人可以提供一些提示如何解決這個問題!

回答

1

這是很容易使用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))); 
相關問題