Collectors
In Java 8, the Collectors
class provides various static methods that allow us to perform reduction operations on streams. A reduction operation combines the elements of a stream into a single result by applying a specified reduction function.
One commonly used collector is summingInt()
, which calculates the sum of the elements in a stream. Here's an example:
TEXT/X-JAVA
1List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
2
3int sum = numbers.stream()
4 .collect(Collectors.summingInt(Integer::intValue));
5
6System.out.println(sum); // Output: 15
In this example, we have a list of integers and we use the stream()
method to create a stream from the list. We then use the summingInt()
collector to calculate the sum of the elements in the stream.
Feel free to modify the list of numbers and see the result!
By using collectors, we can easily perform common reduction tasks on streams without having to write complex logic manually.
xxxxxxxxxx
```java\nclass Main {\n public static void main(String[] args) {\n // replace with your Java logic here\n List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);\n int sum = numbers.stream()\n .collect(Collectors.summingInt(Integer::intValue));\n System.out.println(sum);\n }\n}\n```
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment