比方说,以下是名单 -
List<String> list = Arrays.asList("Welcome", "to","the","club", "club", "the");
不,让我们创建一个映射来获得单词的频率。在这里,我们使用Lambda表达式以及 -
Map<String, Integer> map = list .parallelStream() .flatMap(a -> Arrays.asList(a.split(" ")).stream()) .collect( Collectors.toConcurrentMap(c ->c.toLowerCase(), c -> 1, Integer::sum));
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Demo { public static void main(String[] args) { List<String> list = Arrays.asList("Welcome", "to","the","club", "club", "the"); Map<String, Integer> map = list .parallelStream() .flatMap(a -> Arrays.asList(a.split(" ")).stream()) .collect( Collectors.toConcurrentMap(c ->c.toLowerCase(), c -> 1, Integer::sum)); System.out.println("Word Frequency = "+map); } }输出结果
Word Frequency = {the=2, club=2, to=1, welcome=1}