The Java 8 streams API provides two important operations to work with the data in a stream: map() and reduce(). These operations have different purposes and can be used together to transform and process data in a stream.
The map() operation is used to transform each element in the stream into another element. It takes a lambda expression that specifies how to transform each element, and returns a new stream with the transformed elements. Here’s an example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(n -> n * n)
.collect(Collectors.toList());
In this example, the map() operation is used to transform each number in the stream by squaring it, and the resulting stream of squared numbers is collected into a new list.
The reduce() operation is used to combine all the elements in a stream into a single result. It takes a lambda expression that specifies how to combine two elements, and returns the final result. Here’s an example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
In this example, the reduce() operation is used to sum all the numbers in the stream, starting with an initial value of 0. The lambda expression specifies how to combine two numbers by adding them together.
To summarize, the map() operation is used to transform each element in a stream into another element, while the reduce() operation is used to combine all the elements in a stream into a single result. These operations can be used together to transform and process data in a stream.