Java Stream filter() vs map()

In Java, the filter() and map() methods are commonly used with streams to perform operations on collections of data. These two methods serve different purposes and are used in different scenarios. In this post, we are going to see about Java Stream filter() vs map().

The filter() method is used for boolean conditions (for example a given list of numbers, gets even numbers) whereas the map() method is used to perform some operation(for example for a given list of numbers add 100 to each digit).

filter() Method

The filter() method is used to filter elements from a stream based on a given condition. It takes Predicate as an argument, which is a functional interface that defines a test for each element in the stream. If the test (predicate) returns true for an element, that element is included in the resulting stream; otherwise, it is excluded.

Here’s an example that demonstrates the use of filter() to filter even numbers from a list of integers:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

        // Using filter to get even numbers
        List<Integer> evenNumbers = numbers.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList());

        System.out.println("Even numbers: " + evenNumbers);
    }
}

In this example, the filter() method is used to select only the even numbers from the list, resulting in a new list containing [2, 4, 6, 8, 10].

map() Method

The map() method is used to transform each element in a stream using a given function. It takes Function as an argument, which defines how to map each element in the stream to a new value. The result is a new stream containing the mapped values.

Here’s an example that uses map() to double each number in a list of integers:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

        // Using map to double each number
        List<Integer> doubledNumbers = numbers.stream()
                .map(n -> n * 2)
                .collect(Collectors.toList());

        System.out.println("Doubled numbers: " + doubledNumbers);
    }
}

In this example, the map() method is used to double each number in the list, resulting in a new list containing [2, 4, 6, 8, 10].

To summarize:

  • filter() is used to select elements from a stream based on a condition.
  • map() is used to transform each element in a stream using a function.

Let’s see the difference between filter() and map() using tabular format.

Here’s a tabular representation of four key differences between filter() and map() in Java streams:

filter()map()
Selects elements based on a conditionTransforms elements using a function
Returns a stream of the same typeReturns a stream may different type
Predicate functional interface is used as the argumentA predicate functional interface is used as the argument
Reduces the size of the streamCan change the content and structure of the stream, but the size remains same

Let’s see the explanation for above points ( i.eJava Stream filter() vs map()).

1. Selects elements based on a condition (filter())

  • filter() is used to select elements from a stream based on a condition, allowing only elements that meet the condition to pass through.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

// Use filter() to select even numbers
List<Integer> evenNumbers = numbers.stream()
        .filter(n -> n % 2 == 0)
        .collect(Collectors.toList());

// Result: [2, 4, 6]

In this example, filter() selects only the even numbers from the list.

2. Returns a stream of the same type (filter())

  • filter() returns a stream of the same type as the original stream, preserving the type of elements in the resulting stream.

3. Transforms elements using a function (map())

  • map() is used to transform elements in a stream by applying a function to each element, generating a new value for each element.

Example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Use map() to convert names to uppercase
List<String> upperCaseNames = names.stream()
        .map(String::toUpperCase)
        .collect(Collectors.toList());

// Result: ["ALICE", "BOB", "CHARLIE"]

In this example, map() converts each name to uppercase.

4. Returns a stream of potentially different type (map())

  • map() returns a stream that can potentially have a different type than the original stream, depending on the function applied.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Use map() to square each number
List<Long> squaredNumbers = numbers.stream()
        .map(n -> (long) n * n)
        .collect(Collectors.toList());

// Result: [1L, 4L, 9L, 16L, 25L]

In this example, map() transforms integers into longs by squaring them, resulting in a stream of long values.

These examples illustrate the key differences between filter() and map() in terms of their purposes and behaviors when working with Java streams.

These two methods are often used in combination to perform complex operations on streams of data.

That’s all about Java Stream filter() vs map().

Other Java 8 tutorials.