How has map, filter, reduce changed in recent Java versions?

In recent Java versions, especially since Java 8, the introduction of the Stream API has significantly changed how developers handle collections of data. The methods map, filter, and reduce allow for more concise and functional-style operations on data collections, making code more readable and maintainable.

The map function transforms each element of a stream, filter allows you to exclude elements based on a condition, and reduce aggregates the elements into a single result. These operations can be chained together to create powerful data processing pipelines.

Here’s an example illustrating the use of these methods:

// Example of using map, filter, and reduce in Java import java.util.Arrays; import java.util.List; public class StreamExample { public static void main(String[] args) { List numbers = Arrays.asList(1, 2, 3, 4, 5, 6); int sumOfSquares = numbers.stream() .filter(n -> n % 2 == 0) // filter even numbers .map(n -> n * n) // square them .reduce(0, Integer::sum); // sum them up System.out.println("Sum of squares of even numbers: " + sumOfSquares); // Output: 56 } }

Java Stream API map filter reduce functional programming