【发布时间】:2020-04-07 10:21:26
【问题描述】:
我有两个字符串列表。需要在另一个字符串列表中创建一个列表的每个字符串出现的映射。如果一个字符串出现的次数超过了单个字符串,则应计为一次。
例如:
String[] listA={"the", "you" , "how"};
String[] listB = {"the dog ate the food", "how is the weather" , "how are you"};
Map<String, Integer> map 会将键作为来自listA 的字符串,并将值作为出现。所以 map 的键值是:("the",2)("you",1)("how",2)。
注意:虽然"the" 在"the dog ate the food" 中重复了两次,但它在同一个字符串中只计为一次。
如何使用java-stream 编写此内容?我尝试了这种方法但不起作用:
Set<String> sentenceSet = Stream.of(listB).collect(Collectors.toSet());
Map<String, Long> frequency1 = Stream.of(listA)
.filter(e -> sentenceSet.contains(e))
.collect(Collectors.groupingBy(t -> t, Collectors.counting()));
【问题讨论】:
标签: java-stream java arrays java-8 java-stream