Collectors.summingInt
时间: 2023-08-02 07:05:33 浏览: 124
Java开发你的收集器获得更好的性能.pdf
Collectors.summingInt is a static method in the Java Stream API that returns a collector which calculates the sum of a specified integer attribute in a stream of objects. It is commonly used in conjunction with the Stream.collect method.
Here's an example usage:
```
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.collect(Collectors.summingInt(num -> num));
System.out.println("Sum: " + sum);
}
}
```
In this example, we have a list of integers `numbers`. We use the `stream()` method to create a stream from the list and then apply the `collect` method with `Collectors.summingInt` as the collector. The lambda expression `num -> num` specifies the integer attribute we want to sum. Finally, we print the sum which is the result of the `Collectors.summingInt` operation.
阅读全文