使用 Streams 计算列表中的相同单词

Counting same words in the list by using Streams

如何计算列表中的特定单词并return它作为int

strings.stream().filter(element -> element.equals("")).count();

returns long.

如果很快,如何使用stream编写这段代码?

private static int getCountEmptyStringLoop(List<String> strings) {
        int counter = 0;
        for (int i = 0; i < strings.size(); i++) {
            if (strings.get(i).equals("")){
                counter++;
            }
        }
        return counter;
    }

我开始学习流,但我不太明白它是如何工作的。

public static <T> long countTokens(List<T> list, T token) {
     return list.stream().filter(item -> item.equals(token)).count();
}

只需手动将计数转换为 int:

private static int getCountEmptyStringLoop(List<String> strings) {
    return (int) strings.stream()
                        .filter(""::equals)
                        .count();
}

private static int getCountEmptyStringLoop(List<String> strings) {
    return (int) strings.stream()
                        .filter(Objects::nonNull)
                        .filter(String::isEmpty)
                        .count();
}

问题是您正在使用 count(),这将 return long

请试试:

int count = words.stream()
  .mapToInt(word -> "".equals(word) ? 1 : 0)
  .sum()
;

或:

int count = words.stream()
  .map(word -> "".equals(word) ? 1 : 0)
  .reduce(0, (a, b) -> a + b)
;

非常相似:

int count = words.stream()
  .map(word -> "".equals(word) ? 1 : 0)
  .reduce(0, Integer::sum)
;

或使用收集器:

int count = words.stream()
  .map(word -> "".equals(word) ? 1 : 0)
  .collect(Collectors.summingInt(Integer::intValue))
;

或者,更好的是,按照@Holger 的建议,排成一排:

int count = words.stream()
  .collect(Collectors.summingInt(word -> "".equals(word) ? 1 : 0))
;

所有这些示例都可以包含在一个方法中,更通用的方法如下:

import java.util.Objects;

//...

public int getCount(List<String> terms, String searchTerm) {
  Objects.requireNonNull(terms, "Null terms list provided");

  int count = terms.stream()
      .mapToInt(word -> Objects.equals(searchTerm, word)? 1 : 0)
      .sum();
  ;
  
  return count;
}

在您的用例中:

int countOfEmptyString = getCount(words, "");

附带说明一下,为避免 npe 问题和 null 检查,请始终像这样比较信息("" 永远不会 null):

"".equals(element)

代替(element可以是null):

element.equals("")

顺便说一下,@ETO 的回答也是一个非常合适的选择。