Java方法不打印重复的列表元素

时间:2018-04-17 04:56:11

标签: java

我正在尝试打印存储对象的arraylist的元素。简单地说,我希望方法wordIndexer打印出在对象标题中看到给定单词的次数。在这个例子中,我试图打印"我们"有3次"我们",但不幸的是我只能打印一次。

public class RedditThingIndexer {

    static List<String> words = new ArrayList<>();

    public static String wordIndexer(List<RedditThing> list, String word) {
        int count = 0;
        for (RedditThing thing : list) {
            if (thing.getTitle().toLowerCase().contains(word.toLowerCase())) {
                count++;
                words.add(word);
            }
        }
        return word + " appears: " + count + "\n"
                + "New list: " + words;
    }
}

这是我的方法调用:

System.out.println(RedditThingIndexer.wordIndexer(list, "we"));

以下是我试图提取的文字:

[85kaz5 Why do we use pillows now when we sleep? Did we need this during the prehistoric/ancient age? What changed?  askscience 18563 1521502020 ]

1 个答案:

答案 0 :(得分:1)

public static void wordIndexer() {

    String text = "85kaz5 Why do we use pillows now when we sleep? Did we need this during the prehistoric/ancient age? What changed?  askscience 18563 1521502020";
    String[] words = text.split(" ");
    String wordToMatch = "we";
    int count = 0;
    for (int i=0;i<words.length;i++) {
      if (words[i].toLowerCase().contains(wordToMatch.toLowerCase())) {
        count++;
      }
    }
  }

您可以尝试此解决方案。