【问题标题】:Java - How to get each word from ArrayList of sentencesJava - 如何从句子的 ArrayList 中获取每个单词
【发布时间】:2020-04-29 16:53:01
【问题描述】:

例如,如何检查 listcontainsThese 中的单词是否存在于 listsentences 中以及有多少?

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' ?

}

欢迎提出建议,谢谢。

【问题讨论】:

  • 嗯,有两个想法。 String#contains 和某种 Map 将是一些开始的地方

标签: java arrays arraylist hashmap string-comparison


【解决方案1】:

使用下面的函数,您可以在每个空格处拆分一个句子并将单词添加到一个新列表中。

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;
}

返回 -> {warm day=[day], sounds good=[good], wish you a good day=[good, day]}

【讨论】:

  • 所以,你已经回答了大约 1/3 的问题......但我想知道为什么在这种情况下你甚至都使用 List,而不是仅仅使用从split返回数组
【解决方案2】:

为了获得最佳性能,首先构建句子中所有单词的Set,然后计算可以在集合中找到的单词。

List<String> sentences = Arrays.asList("wish you a good day", "warm day", "sounds good");
List<String> containsThese = Arrays.asList("cool", "day", "good");

Set<String> words = sentences.stream()
        .flatMap(Pattern.compile("\\s+")::splitAsStream)
        .collect(Collectors.toSet());
long wordsFound = containsThese.stream()
        .filter(words::contains)
        .count();

System.out.printf("Sentences contains %d of %d words%n", wordsFound, containsThese.size());

输出

Sentences contains 2 of 3 words

【讨论】:

    【解决方案3】:
    List<String> sentences = ArrayList<String>("wish you a good day", "warm day", "sounds good");
    Iterator itr=sentences.iterator();
    while(itr.hasNext()){
    String s=itr.next();
    }
    

    【讨论】:

    • 感谢您在 StackOverflow 上发布您的第一个答案!但是,我们要求您在回答问题时描述您为解决问题所做的工作,以便提问者能够更好地理解您的解决方案。
    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多