Java - 搜索字符串列表,如果包含另一个字符串列表

时间:2016-09-17 16:39:40

标签: java for-loop

我有用户推文列表(usersTweets),我需要查找包含特定关键字(listOfkeyWord)的推文,并将匹配添加到(includeKeyWord)列表。

    String keyWord = "one,two";
    List<String> usersTweets = new ArrayList<String>();
    usersTweets.add("three nine one two");
    usersTweets.add("seven one");
    usersTweets.add("three nine ten one");
    usersTweets.add("....");

    List<String> includeKeyWord = new LinkedList<String>();

    if (keyWord.contains(",")) {
        List<String> listOfkeyWord = new ArrayList<String>(Arrays.asList(keyWord.split(",")));
        for (String tweet : usersTweets) {
            if (tweet.contains(listOfkeyWord)) {
                includeKeyWord.add(tweet);
            }
        }
    }

注意:

如果它包含一个关键词列表,如何检查每条推文。在这个例子中我想要(includeKeyWord)只有字符串“三个九一二”,因为它有“一个”和“两个”字样”

2 个答案:

答案 0 :(得分:0)

基本上你想检查tweet是否包含所有单词,所以你需要遍历这些单词的列表并检查你的推文是否包含所有单词,你可以这样做:

public boolean hasAllTheWords(String yourString, List<String> words){
  for(String word : words)
    if(!yourString.contains(word))
      return false
  return true;
}

现在代替tweet.contains(words) hasAllTheWords(tweet, words)。您还可以将推文转换为单词列表,然后将您已有的内容转换为tweet.contains(words)),这样您也可以尝试:

Arrays.asList(tweet.split(" ")).contains(words)

如果您尝试该解决方案,请记住处理标点符号(, . ... ! ?等)。

答案 1 :(得分:0)

  

在这里(完整的例子):

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Example {

    /**
     * Constructor
     */
    public Example() {

        //List of usersTweets
        List<String> usersTweets = new ArrayList<>();
        usersTweets.add("three nine one two");
        usersTweets.add("seven one");
        usersTweets.add("three nine ten one");
        usersTweets.add("....");

        //The keyWord
        String keyWord = "one,two";


        //make keyWord a List of words
        List<String> listOfkeyWord = new ArrayList<>(Arrays.asList(keyWord.split(",")));

        // Filter every word in the list usersTweets
        //if it contains all the words from listOfKeyWord 
        //then collect all them into a List
        List<String> includeKeyWord = usersTweets.stream()
                                                 .filter(tweet -> listOfkeyWord.stream()
                                                                               .allMatch(tweet::contains)) //word -> tweet.contains(word))
                                                 .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        new Example();
    }
}