如何计算我在ArrayList中有多少个出现的词?

时间:2015-07-15 23:07:42

标签: java

如何计算我在ArrayList中拥有的单词的数量?有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:1)

如果您只想找到多少场比赛并且您不需要知道位置,请尝试使用此

BufferedReader reader = new BufferedReader(new FileReader("hello.txt"));
    StringBuilder builder = new StringBuilder();
    String str = null;
    while((str = reader.readLine()) != null){
        builder.append(str);
    }

    String fileString = builder.toString();
    String match = "wordToMatch";
    String[] split = fileString.split(match);
    System.out.println(split.length - 1);//finds amount matching exact sentance

答案 1 :(得分:0)

试试这个:

private static int findMatches(List<Character> text, List<Character> pattern) {
    int n = text.size();
    int m = pattern.size();
    int count = 0;  // tracks number of matches found

    for (int i = 0; i <= n - m; i++) { 
        int k = 0;
        while (k < m && text.get(i + k) == pattern.get(k))
        k++;
        if (k == m) { // if we reach the end of the pattern
            k = 0;
            count++;
        }
    }
    return count;
}

答案 2 :(得分:0)

使用List<String>代替List<Character>。之后,您可以强制使用Java 8的流并过滤。

public static void main(String[] args) throws Exception {
    List<String> words = new ArrayList() {{
        add("one");
        add("two");
        add("one");
        add("one");
        add("two");
        add("one");
        add("two");
        add("three");
        add("one");
        add("one");
    }};

    String wordToSearch = "one";

    int occurrence = 0;
    for (String word : words) {
        if (word.equals(wordToSearch)) {
            occurrence++;
        }
    }
    System.out.println("Brute force: " + occurrence);
    System.out.println("Streams    : " + words.stream()
            .filter(word -> word.equalsIgnoreCase(wordToSearch)).count());
}

结果:

Brute force: 6
Streams    : 6