DEV Community

Cover image for Java Streams Made Simple: map() and filter() Explained
Md. Monowarul Amin
Md. Monowarul Amin

Posted on

Java Streams Made Simple: map() and filter() Explained

Java Streams Made Simple: map() and filter() Explained

The Java Stream API lets you describe what you want to do with a collection of data instead of writing the loop yourself. In this post we cover its two most basic operations, filter() and map(), step by step.


Step 1: What is a Stream?

A stream is simply a sequence of data values. It can be created from a collection, an array, or other data sources. Streams were introduced in Java 8 and live in the package java.util.stream.

Two things to remember:

  • A stream does not store data; it describes a flow of values through a series of operations.
  • A stream can be used only once. To use the data again, create a new stream from the same source.

Step 2: The Stream Pattern

Every stream computation follows the same pattern:

create stream  ->  apply intermediate operator(s)  ->  apply terminal operator
Enter fullscreen mode Exit fullscreen mode
Part What it does Examples
Create stream Gets data from a source list.stream(), Arrays.stream(arr), IntStream.range(a, b)
Intermediate operator Turns a stream into another stream (chainable) filter(), map(), sorted(), limit()
Terminal operator Ends the pipeline with a result that is not a stream collect(), forEach(), count(), sum()

Intermediate operators are lazy: nothing runs until a terminal operator is called.


Step 3: filter() runs on a Predicate

A predicate is a function that returns a boolean. In Java it is the functional interface Predicate<T>, with the method boolean test(T t).

filter() takes a predicate and creates a new stream containing only the values for which the predicate is true.

Our predicate will be an isPrime(n) method that tests whether n is prime. This is the example from the book:

IntStream.range(2, 1000).filter( n -> isPrime(n) )
Enter fullscreen mode Exit fullscreen mode

This creates a stream of all the prime numbers from 2 to 999.


Step 4: map() runs on a Function

A function takes a value and returns a value. In Java it is the functional interface Function<T, R>, with the method R apply(T t).

map() applies the function to every value in the stream and creates a new stream made of the values the function returned.

filter() map()
Runs on Predicate Function
Lambda returns a boolean any value
Purpose Select items to keep Transform every item
Output size Same or smaller Always the same

Step 5: See the Difference with isPrime()

We will use the same isPrime(n) method in both operations and run them on two inputs:

  • Input A: [1, 2, 3, 4, 5]
  • Input B: [6, 7, 8, 9, 10]

filter() with isPrime: keeps the values that pass

list.stream().filter( n -> isPrime(n) ).collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
Input A: [1, 2, 3, 4, 5]   ->  [2, 3, 5]
Input B: [6, 7, 8, 9, 10]  ->  [7]
Enter fullscreen mode Exit fullscreen mode

The predicate answered true/false for each number, and only the "true" ones were kept. The values themselves did not change.

map() with isPrime: replaces each value with the function's result

list.stream().map( n -> isPrime(n) ).collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
Input A: [1, 2, 3, 4, 5]   ->  [false, true, true, false, true]
Input B: [6, 7, 8, 9, 10]  ->  [false, true, false, false, false]
Enter fullscreen mode Exit fullscreen mode

Every number was replaced by what isPrime returned, so we get one output per input. This is the key difference: filter() uses the boolean to decide what to keep, while map() keeps the returned value itself.


Cheat Sheet

  • Stream: a sequence of data values.
  • Pattern: create stream, then intermediate operator(s), then terminal operator.
  • Predicate: returns a boolean. filter(Predicate) keeps the items where it is true.
  • Function: returns a value. map(Function) replaces each item with that value.

Try it yourself: swap isPrime for your own method (for example, isEven) and see how the outputs change.


Reference

  • Eck, David J. Introduction to Programming Using Java, Version 9 (Javanotes 9), Section 10.6: Introduction to the Stream API.

Top comments (0)