示例,如何检查列表 containsThese
中的单词是否存在出现在列表中sentences
有多少?
List<String> sentences = Arrays.asList("wish you a good day", "warm day", "sounds good");
List<String> containsThese = Arrays.asList("cool", "day", "good");
我在做什么:
for (int i = 0; i < sentences.size(); i++){
String words = sentences.get(i);
// so here I have each sentence separately
// but how to iterate through it and add each word to another ArrayList or something?
// so later can compare to it to 'containsThese' ?
}
欢迎大家提出建议,谢谢。
最佳答案
使用下面的函数,您可以在每个空格处拆分句子并将单词添加到新列表中。
private List<String> sentenceToList(String sentence) {
return new ArrayList<>(Arrays.asList(sentence.split("\\s+")));
}
通过此函数,您将获得一个 Map,其中以句子为键,并包含一个包含来自 containsThese 的所有单词的列表。
private Map<String, List<String>> checkSentences() {
Map<String, List<String>> containsMap = new HashMap<>();
sentences.forEach(sentence -> {
containsMap.put(sentence, sentenceToList(sentence).stream().distinct().filter(word -> containsThese.contains(word)).collect(Collectors.toList()));
});
return containsMap;
}
返回-> {温暖的一天=[day],听起来不错=[good],祝你有美好的一天=[good, day]}
关于Java - 如何从句子的ArrayList中获取每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708779/