Java 计算字符串的ArrayList中单词的出现次数

Java 计算字符串的ArrayList中单词的出现次数,java,arraylist,Java,Arraylist,我有一个很大的字符串数组列表。列表中的每个字符串元素也相当大。我想计算单词“the”在列表的每个元素中出现的次数。我当前的代码只遍历索引1。如何使它对数组的所有元素都计数 public static int counter(List<String> comments) { for (String comment : comments.subList(1, comments.size() - 1)) { String a[] = comment.split("

我有一个很大的字符串数组列表。列表中的每个字符串元素也相当大。我想计算单词“the”在列表的每个元素中出现的次数。我当前的代码只遍历索引1。如何使它对数组的所有元素都计数

public static int counter(List<String> comments) {
    for (String comment : comments.subList(1, comments.size() - 1)) {

        String a[] = comment.split(" ");

        String word = "the";
        int count = 0;
        for (int j = 0; j < a.length; j++) {

            if (word.equals(a[j])) {
                count++;
            }
        }
        System.out.println(comment);
        return count;
    }
    System.out.println("sefsfsfseesfeseeeeeeeeeeeeeeeeeeeeeee");
    return 0;
}
公共静态整数计数器(列表注释){
for(字符串注释:comments.subList(1,comments.size()-1)){
字符串a[]=comment.split(“”);
String word=“the”;
整数计数=0;
对于(int j=0;j
不要调用
子列表
并在迭代整个列表后返回:

public static int counter(List<String> comments) {
    int count = 0;
    String word = "the";
    for (String comment : comments) {
        String a[] = comment.split(" ");
        for (int j = 0; j < a.length; j++) {
            if (word.equals(a[j])) {
                count++;
            }
        }
        System.out.println(comment);
    }
    System.out.println("sefsfsfseesfeseeeeeeeeeeeeeeeeeeeeeee");
    return count;
}
公共静态整数计数器(列表注释){
整数计数=0;
String word=“the”;
for(字符串注释:注释){
字符串a[]=comment.split(“”);
对于(int j=0;j
您的方法类型不正确,应该是
Map
如果您使用的是Java 8,则可以创建每个单词及其频率的映射,如下所示:

Map<String, Long> result = comments.stream()
    .flatMap(comment -> Stream.of(comment.split("\\s+")))
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
或者只是:

Long count = comments.stream()
        .flatMap(comment -> Stream.of(comment.split("\\s+")))
        .filter(s -> s.equals(word))
        .count();

您希望每个元素单独计数,还是整个列表中的总计数?到目前为止,主要的问题似乎是for循环中的返回,在第一个元素之后立即停止该方法。我希望得到整个列表的总计数。索引0为空,这就是我使用子列表的原因。我建议您阅读一些调试自己代码的提示,以了解可能重复的子列表。您犯了一个小错误,这些提示应该可以帮助您找到它。请参阅如何跳过for循环中的第一个索引这是朝着正确方向迈出的一步。然而,当我使用for-each循环打印列表中的每个注释时,我将输出复制并粘贴到word中,然后搜索“the”,总数为423。计数器方法仅显示248。“这是怎么回事?”我更新了答案。也许有一些单词像
他们
,你可以搜索它。但是它不会被计算在内。你可能必须通过只测试而不是测试来将两个字符串转换为小写。这可能会遗漏“the”,“aw man,microsoft word显然是在计算出现在“他们”等中的“the”,这是一个愚蠢的错误。
Long count = comments.stream()
        .flatMap(comment -> Stream.of(comment.split("\\s+")))
        .filter(s -> s.equals(word))
        .count();