使用JavaStreams返回出现单词的句子的计数和列表

我被困在试图找出每个单词出现的句子中。该条目将是一个句子列表

Question, what kind of wine is best? 
White wine.
A question

输出将是

// format would be: word:{count: sentence1, sentence2,...}
a:{1:3} 
wine:{2:1,2} 
best:{1:1} 
is:{1:1} 
kind:{1:1} 
of:{1:1} 
question:{2:1,3} 
what:{1:1}
white:{1:2}

这是我到目前为止所得到的:

static void getFrequency(List<String> inputLines) {
  List<String> list = inputLines.stream()
     .map(w -> w.split("[^a-zA-Z0-9]+"))
     .flatMap(Arrays::stream)
     .map(String::toLowerCase)
     .collect(Collectors.toList());

   Map<String, Integer> wordCounter = list.stream()
     .collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));
}

有了这个,我只能得到每个单词出现在所有句子中的次数,但我还需要获得该单词出现的句子列表。看起来也许是为了获取我可以使用的句子的 id IntStream.range,如下所示:

 IntStream.range(1, inputLines.size())
          .mapToObj(i -> inputLines.get(i));

但我不确定这是否是最好的方法,我是 Java 新手

回答

您可以使用分组收集器来计算单词到索引列表映射。下面是一个例子:

private static Map<String, List<Integer>> getFrequency(List<String> inputLines) {
    return IntStream.range(0, inputLines.size())
            .mapToObj(line -> Arrays.stream(inputLines.get(line)
                 .split("[^a-zA-Z0-9]+"))
                 .map(word -> new SimpleEntry<>(word.toLowerCase(), line + 1)))
            .flatMap(Function.identity())
            .collect(Collectors.groupingBy(Entry::getKey, 
                  Collectors.mapping(Entry::getValue, Collectors.toList())));
}

有了你的测试数据,我得到

{a=[3], what=[1], white=[2], question=[1, 3], kind=[1], 
 of=[1], best=[1], is=[1], wine=[1, 2]}

计数很容易从列表大小推断出来,因此不需要额外的类。

  • @ernest_k, I was checking the problem and they don't specify if the sentenceid should be repeated for each time it appears in a sentence, it looks like its just to know where it appears, for now I think is ok as you have your answer

以上是使用JavaStreams返回出现单词的句子的计数和列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>