Skip to content
章节导航

Collectors.counting()

Collectors.counting() 是用于统计流中元素数量的收集器,返回 Long 类型的计数结果。

基本用法

java
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
 
 // 1. 基本用法 - 统计元素个数
 Long count = names.stream()
     .collect(Collectors.counting());
 
 System.out.println("Total names: " + count); // 4
 
 // 2. 使用 count() 简化(推荐)
 long simpleCount = names.stream().count();
 System.out.println("Simple count: " + simpleCount); // 4
 
 // 3. 配合 filter 使用
 Long countStartWithA = names.stream()
     .filter(name -> name.startsWith("A"))
     .collect(Collectors.counting());
 
 System.out.println("Names starting with A: " + countStartWithA); // 1

核心特性

1. 返回类型为 Long

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
 
 // counting() 返回 Long 类型
 Long count = numbers.stream()
     .collect(Collectors.counting());
 
 System.out.println("Count: " + count);
 System.out.println("Type: " + count.getClass()); // java.lang.Long
 
 // 与 int 类型的区别
 int intCount = (int) numbers.stream().count(); // 需要类型转换
 System.out.println("Int count: " + intCount);
 
 // 处理大数量时 Long 的优势
 List<Integer> largeList = IntStream.range(0, 1_000_000)
     .boxed()
     .collect(Collectors.toList());
 
 Long largeCount = largeList.stream()
     .collect(Collectors.counting());
 
 System.out.println("Large count: " + largeCount); // 1000000

2. 空流处理

java
// 空流返回 0L
 Long emptyCount = Stream.<String>empty()
     .collect(Collectors.counting());
 
 System.out.println("Empty stream count: " + emptyCount); // 0
 
 // 包含 null 的流
 List<String> withNulls = Arrays.asList("Alice", null, "Bob", null, "Charlie");
 
 // 统计非 null 元素
 Long nonNullCount = withNulls.stream()
     .filter(Objects::nonNull)
     .collect(Collectors.counting());
 
 System.out.println("Non-null elements: " + nonNullCount); // 3
 
 // 统计 null 元素
 Long nullCount = withNulls.stream()
     .filter(Objects::isNull)
     .collect(Collectors.counting());
 
 System.out.println("Null elements: " + nullCount); // 2