Core Java

Java 8 filter & map & collect & Stream Example

Hello guys, many of my readers emailed me to write a post about map and filter function of Java 8 because they found it difficult to understand and use. Even though I have previously blogged about both map() and filter(), I am writing this post again to explain the concept in more layman’s language for better understanding of my readers and fellow Java developers.

The map() function is a method in Stream class which represent a functional programming concept. In simple words, the map() is used to transform one object into other by applying a function.

That’s the reason the Stream.map(Function mapper) takes a function as an argument. For example, by using map() function you can convert a list of String into List of Integer by applying Integer.valueOf() method to each String on the input list.

All you need is a mapping function to convert one object to other and the map() function will do the transformation for you.

It is also an intermediate stream operation which means you can call other Stream methods like a filter or collect on this to create a chain of transformation.

Now, coming to filter method, as its name suggests, it filters elements based upon a condition you gave it to you. For example, if your list contains numbers and you only want even numbers then you can use filter method to the only select number which is fully divisible by two.

The filter method essentially select elements based upon condition you provide. That’s the reason that filter(Predicate condition) accept a Predicate object which provides a function to apply a condition. If the condition evaluates true then the object is selected otherwise it is ignored.

Similar to map, the filter is also an intermediate operation which means you can call other Stream methods after calling filter.

The filter() method is also lazy which means it will not be evaluated until you call a reduction method like collect and it will stop as soon as it reaches the target.

1. How to use map and filter in Java 8

You need a good example to understand a new concept and that’s why you are reading this article. Since String and Integer are most common data type in Java, I have chosen an example which is both simple and interesting.

I have a list of String which is numbers e.g. {"1", "2", "3", "4", "5", "6"} I want to process this list and need another List of Integer with just even numbers.

In order to find the even number I first need to convert a List of String to List of Integer and for that, I can use the map() method of java.util.Stream class, but before that we need a Stream as a map() is defined in java.util.stream. Stream class.

But, that’s not difficult at all, as you can get the stream from any Collection e.g. List or Set by calling the stream() method because it defined in java.util.Collection interface.

The map(Function mapper) method takes a Function, technically speaking an object of java.util.function.Function interface. This function is then applied to each element of Stream to convert into a type you want.

Since, we need to convert an String to Integer, we can pass either Integer.parseInt() or Integer.valueOf() method to map() function. I have chose valueOf() method because of the reasons I mentioned in parseInt vs valueOf article i.e. performance and caching.

The map() will then return a Stream of Integer which contains both even and odd number. To select just even numbers, we can use the filter() method. It takes a Predicate object which is technically a function to convert an object to boolean. I mean we pass an object and it will return true or false. the filter uses that information to include the object in the result stream.

So, to include only even numbers we call filter( number -> number%2==0) which means each number will be divided by zero and if there is no remainder then it will be selected.

We are almost done, but so far we only have Stream of even integers not the List of even Integers and that’s why we need to use the collect() method, which collects elements form Stream into a specified Collection.

Since we need List, I called collect(Collectors.toList()) which will accumulate all even numbers into a List and return. Now you may be thinking how does it know to return List of Integer, well it get that information by Type inference because we have already specified that by storing the result into a List<Integer>.

2. Java 8 Map + Filter + Collect Example

Here is the Java program to implement whatever I have said in the above section. You can run this program in IDE or from the command line and see the result. You can also experiment with using more map() function or more filter() calls to make the composition longer and more sophisticated. You can even play with collect() method to collect the result in a list, set, map or any other collection.

package tool;

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

/**
 * 
 * A simple Java Program to demonstrate how to use map and filter method Java 8.
 * In this program, we'll convert a list of String into a list of Integer and
 * then filter all even numbers.
 */
public class Hello {

  public static void main(String[] args) {

    List<String> numbers = Arrays.asList("1", "2", "3", "4", "5", "6");
    System.out.println("original list: " + numbers);

    List<Integer> even = numbers.stream()
                                .map(s -> Integer.valueOf(s))
                                .filter(number -> number % 2 == 0)
                                .collect(Collectors.toList());

    System.out.println("processed list, only even numbers: " + even);

  }

}

Output
original list: [1, 2, 3, 4, 5, 6]
the processed list, only even numbers: [2, 4, 6]

You can see that original list contains numbers from 1 to 6 and the filtered list only contains even numbers i.e. 2, 4, and 6.

The most important code in this example is the following 4 lines of Stream processing code:

This code is first doing a map and then filter and finally collect. You may be wondering whether the order will matter or not, well it does. Since our filter condition requires an int variable we first need to convert Stream of String to Stream of Integer, that’s why we called map() function first.

Once we got the Stream of Integer we can apply maths to find out even numbers and we passed that condition to filter method.

If we needed to filter on String e.g. select all string which has length > 2 then we would have called filter before map.

That’s all about how to use map and filter in Java 8. We have seen an interesting example of how we can use the map to transform an object to another and filter to select an object based upon condition. We have also learned how to compose operations on stream to write code which is both clear and concise.

Thanks for reading this tutorial so far. If you like this Java 8 map + filter example and my explanation then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

Published on Java Code Geeks with permission by Javin Paul, partner at our JCG program. See the original article here: Java 8 filter + map + collect + Stream Example

Opinions expressed by Java Code Geeks contributors are their own.

Javin Paul

I have been working in Java, FIX Tutorial and Tibco RV messaging technology from past 7 years. I am interested in writing and meeting people, reading and learning about new subjects.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tony
Tony
6 years ago

Article states: “So, to include only even numbers we call filter( number -> number%2==0) which means each number will be divided by zero and if there is no remainder then it will be selected.”

I believe this is a typo and should really be:
“…divided by 2…”

Alejandro Colomer
Alejandro Colomer
6 years ago

Sorry I ment to give a thumbs up, good example.

Bill Fly
Bill Fly
6 years ago

The stream works very well. It can process 45,000,000 random longs for even or odd in 1 – 3 seconds. The parallelStream does not make that much difference in this case.

Muralidharan Narayana
Muralidharan Narayana
5 months ago

Well explained

Back to top button