collect(Collectors.counting())
时间: 2023-10-15 18:02:36 浏览: 95
collector
The `Collectors.counting()` method is a built-in collector in Java that returns a `Collector` that counts the number of elements in a stream.
For example, if we have a stream of integers and we want to count the number of elements in the stream, we can use `Collectors.counting()` as follows:
```
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().collect(Collectors.counting());
System.out.println(count); // Output: 5
```
In this example, the `collect()` method is used to collect the stream elements using the `Collectors.counting()` method, which returns the number of elements in the stream. The result is stored in the `count` variable and printed to the console.
阅读全文