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.
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:
Mapping to Square Values
The map method is used to transform elements within a stream. You provide a function that defines the transformation.
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:
