Intermediate Operations: Filtering, Mapping, and Transforming Streams

Filtering, Mapping, and Transforming Streams

Welcome back! Now that you have a basic understanding of Java Streams and how to create and use them, it’s time to dive into some more powerful stream operations. In this lesson, we will focus on intermediate operations such as filtering, mapping, and transforming streams. These operations will enable you to manipulate data more effectively and make your code cleaner and more efficient.

What You'll Learn

  • How to filter elements in a stream based on a condition.
  • How to transform elements in a stream using mapping.
  • How to flatten a list of lists using flatMap.

By the end of this lesson, you’ll be proficient in using these intermediate operations, allowing you to perform complex data transformations with ease.

Intermediate Stream Operations

Intermediate operations allow you to process and transform data within streams. Unlike terminal operations, intermediate operations are lazy and do not execute until a terminal operation is invoked. Let's break down a few key intermediate operations with examples.

Filtering Even Numbers

To filter elements in a stream, you can use the filter method. This allows you to include only the elements that match a given condition.

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

numbers.stream()
       .filter(n -> n % 2 == 0)
       .forEach(n -> System.out.println("Even number: " + n));

We start with a list of integers. The filter method takes a predicate (a function that returns a boolean) and includes only the elements that match the condition (n % 2 == 0 means the number is even). The result is printed directly using the forEach method.

Output:

Even number: 2
Even number: 4

Mapping to Square Values

The map method is used to transform elements within a stream. You provide a function that defines the transformation.

numbers.stream()
       .map(n -> n * n)
       .forEach(s -> System.out.println("Square: " + s));

Here, we use the same list of integers. The map method takes a function (n -> n * n) that squares each element. The result is printed directly using the forEach method.

Output:

Square: 1
Square: 4
Square: 9
Square: 16
Square: 25
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal