Filter-Map-Reduce in Java

Java 8 introduced several functional programming concepts, including the Stream API, which provides a convenient way to filter, map, and reduce collections.

Here's an example of using the Stream API to filter, map, and reduce a list of integers:

import java.util.Arrays;
import java.util.List;

public class FilterMapReduceExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Filter the list to keep only even numbers
        List<Integer> evenNumbers = numbers.stream()
                                           .filter(n -> n % 2 == 0)
                                           .collect(Collectors.toList());
        System.out.println("Even numbers: " + evenNumbers);

        // Map the list to square each number
        List<Integer> squaredNumbers = numbers.stream()
                                              .map(n -> n * n)
                                              .collect(Collectors.toList());
        System.out.println("Squared numbers: " + squaredNumbers);

        // Reduce the list to calculate the sum of the numbers
        int sum = numbers.stream().reduce(0, Integer::sum);
        System.out.println("Sum: " + sum);
    }
}

In this example, we have a list of numbers and we are using the filter method to keep only even numbers, map method to square each number and reduce method to calculate the sum of the numbers.

  • filter method is used to filter out elements from the stream, it takes a Predicate as a parameter and applies it to each element in the stream.
  • map method is used to transform elements of the stream. It takes a Function as a parameter and applies it to each element in the stream.
  • reduce method is used to combine all elements of the stream into a single value. It takes two parameters: an initial value and a BinaryOperator (a function that takes two values and returns a new one).

Please note that, the filter, map and reduce operations are performed on the stream of data and not on the original data, so it does not modify the original list.

Also, the Collectors.toList() is used to collect the result of the above operations into a list.