Java 8 Functional Programming Example with Stream, map, filter, and collect methods
Tags: java, programming, coding, development
Published: 2020-09-25 04:48:09

---
title: Java 8 Functional Programming Example with Stream, map, filter, and collect methods
published: true
description: You can write powerful functional code in Java using Stream API and lambda expression. In this example, you will learn how to use map, filter, and collect method for writing clean functional code in Java. 
tags: Java, programming, coding, development
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/2ktpko0h30mr5umqkb4t.png
---
*Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.*

Hello, folks! If you are learning functional programming in Java and want to learn how to use map, filter, and collect methods in Java then you have come to the right place.

In the past, I have shared the [best Java functional programming courses](https://javarevisited.blogspot.com/2020/04/top-5-courses-to-learn-functional-programming-in-java-with-lambda-and-stream.html) as well as some [Java books on Lambda and Stream](https://medium.com/javarevisited/7-best-java-tutorials-and-books-to-learn-lambda-expression-and-stream-api-and-other-features-3083e6038e14), and today, I am going to teach you how you can use map, filter, and collect() methods to create your stream pipeline to transform your data from one form to other.

Even though I have previously blogged about both the [map()](http://www.java67.com/2015/01/java-8-map-function-examples.html) and [filter()](http://www.java67.com/2016/08/java-8-stream-filter-method-example.html), I am writing this post again to expand on the concept in a layman's language to provide a better understanding for my readers and fellow Java developers.

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

That's the reason the `Stream.map(Function mapper)` takes a function as an argument. For example, by using the `map()` function, you can convert a list of String into a List of Integer by applying the [Integer.valueOf()](https://javarevisited.blogspot.sg/2011/08/convert-string-to-integer-to-string.html) method to each String on the input list.

All you need is a mapping function to convert one object to the other. Then, the [map()](https://javarevisited.blogspot.sg/2016/03/difference-between-map-and-flatmap-in-java8.html) 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 transformations.

Now, coming to the [filter](http://www.java67.com/2018/03/java-8-stream-find-first-and-filter-example.html) method, as its name suggests, **it filters elements based upon a condition** you gave it. For example, if your list contains numbers and you only want numbers, then you can use the filter method to only select a number that is fully divisible by two.

The filter method essentially selects elements based upon a condition you provide. That's the reason that the filter (`Predicate` condition) accepts a Predicate object, which provides a function that is applied to a condition. If the condition evaluates true, then the object is selected. Otherwise, it will be ignored.

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

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

If you are not familiar with Stream behavior, I suggest you check out [**Learn Java Functional Programming with Lambdas & Streams**](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Ffunctional-programming-with-java%2F) by Ranga Rao Karnam on Udemy, which explains Stream fundamentals in good detail.



## 1\. How to write functional code in Java using Lambda and Stream
You need a good example to understand any new concept. That's why you are reading this article. Since [String](http://www.java67.com/2012/12/how-to-reverse-string-in-java-stringbuffer-stringbuilder.html) and [Integer](https://javarevisited.blogspot.sg/2011/08/convert-string-to-integer-to-string.html) are the most common data type in Java, I have chosen an example which is both simple and interesting.

I have a list of String: numbers like `{"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 numbers, I first need to convert a List of String to a List of Integer. For that, I can use the [map()](http://www.java67.com/2016/09/map-reduce-example-java8.html) method of java.util.Stream class. But, before that, we need a [Stream](http://www.java67.com/2014/04/java-8-stream-examples-and-tutorial.html) as a map() as defined in the java.util.stream class.

This is not difficult at all since you can get the stream from any collection, like [List](http://www.java67.com/2012/07/sort-list-ascending-descending-order-set-arraylist.html) or [Set](http://javarevisited.blogspot.sg/2018/02/java-9-example-factory-methods-for-collections-immutable-list-set-map.html), by calling the stream() method, which is defined in the `java.util.Collection` interface.

The `map(Function mapper)` method takes a [Function](https://javarevisited.blogspot.sg/2018/01/what-is-functional-interface-in-java-8.html), technically speaking, an object of java.util.function.Function interface. This function is then applied to each element of Stream to convert it into the type you want.

Since we need to convert a String to an Integer, we can pass either the `Integer.parseInt()` or `Integer.valueOf()` method to the [map() function](https://www.java67.com/2015/01/java-8-map-function-examples.html).

I have chosen the `valueOf()` method because of the reasons I mentioned in the parseInt vs valueOf article, i.e. performance and caching. By the way, it's not just me. Even Joshua Bloch has advised preferring static factory methods like `valueOf()` over constructor in [*Effective Java*](https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997/?tag=javamysqlanta-20).

The `map()` will then return a Stream of Integer which contains both even and odd numbers. To select just even numbers, we can use the filter() method.

It takes a [predicate](http://javarevisited.blogspot.sg/2015/02/how-to-filter-collections-in-java-8.html) object which is technically **a function to convert an object to boolean**. We pass an object and it will return true or false. The filter, then, 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 two, and if there is no remainder, then it will be selected. This is the same logic we have used while solving coding problems to [check if a given number is even or odd](http://www.java67.com/2018/05/top-75-programming-interview-questions-answers.html) in Java.

We are almost done. But, so far, we only have the Stream of even integers --- not the List of even Integers and that's why we need to use them.

Since we need a 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, we need to get that information by Type inference, because we have already specified that information by storing the result into a `List<Integer>`.

If you want to know more about type inference in a lambda expression,[**The Complete Java MasterClass**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)is a good place to start.

[![](https://cdn-images-1.medium.com/max/667/0*kLriPzotQNnsh2Cj.png)](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)


### 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](https://medium.com/javarevisited/7-best-courses-to-learn-intellij-idea-for-beginners-and-experienced-java-programmers-2e9aa9bb0c05) or from the command line and see the result.

You can also experiment with using more `map()` functions or more `filter()` calls to make the composition longer and more sophisticated. You can even play with the `collect()` method to collect the result in a [list](https://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html), [set](https://javarevisited.blogspot.com/2016/01/3-ways-to-loop-over-set-or-hashset-in-java.html), [map](http://www.java67.com/2017/08/top-10-java-hashmap-interview-questions.html) or any other collection.

You can see that the original list contains numbers from 1 to 6, and the filtered list only contains [even numbers](http://javarevisited.blogspot.sg/2013/04/how-to-check-if-number-is-even-or-odd.html), I mean, 2, 4, and 6.

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

[![](https://cdn-images-1.medium.com/max/667/1*IQdszBCiEV8Xa_RqUhv6OQ.png)](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Ffunctional-programming-with-java%2F)

This code is starting with a map, then a filter, and finally a 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 the **map()** function first.

Once we have the Stream of Integer, we can apply maths to find out even numbers. We passed that condition to the filter method. If we needed to filter on String, like 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 how to use the filter to select an object-based upon condition. We have also learned how to compose operations on stream to write code that is both clear and concise.

**Further Learning**
 [The Complete Java MasterClass](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fjava-the-complete-java-developer-course%2F)
[From Collections to Streams in Java 8 Using Lambda Expressions](https://pluralsight.pxf.io/c/1193463/424552/7490?u=https%3A%2F%2Fwww.pluralsight.com%2Fcourses%2Fjava-8-lambda-expressions-collections-streams)
 [Java SE 8 for Programmers (book)](https://www.amazon.com/Java-SE8-Programmers-Deitel-Developer/dp/0133891380?tag=javamysqlanta-20)
 [Refactoring to Java 8 Streams and Lambdas Self- Study Workshop](https://learning.javaspecialists.eu/courses/refactoring2j8?affcode=92815_johrd7r8)



Other **Java tutorials** you may like
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:

-   The 2020 Java Developer RoadMap ([see](https://javarevisited.blogspot.com/2019/10/the-java-developer-roadmap.html#axzz64YOHJ2TL))
-   How to sort the may by values in Java 8? ([example](http://www.java67.com/2017/07/how-to-sort-map-by-values-in-java-8.html))
-   Difference between map() and flatMap in Java 8 ([answer](https://javarevisited.blogspot.com/2016/03/difference-between-map-and-flatmap-in-java8.html))
-   How to use Stream class in Java 8 ([tutorial](http://www.java67.com/2014/04/java-8-stream-examples-and-tutorial.html))
-   10 Courses to learn Java in-depth ([courses](https://medium.com/javarevisited/top-5-java-online-courses-for-beginners-best-of-lot-1e1e240a758))
-   How to format/parse the date with LocalDateTime in Java 8? ([tutorial](http://javarevisited.blogspot.sg/2017/08/how-to-format-parse-dates-with-LocalDateTime-Java-8.html))
-   5 Books to Learn Java 8 from Scratch ([books](http://javarevisited.blogspot.sg/2016/10/best-books-to-learn-java-8.html))
-   What is the default method in Java 8? ([example](http://www.java67.com/2017/08/java-8-default-methods-on-interface-example.html))
-   How to join String in Java 8 ([example](http://www.java67.com/2016/08/java-8-stringjoin-example.html))
-   Difference between abstract class and interface in Java 8? ([answer](http://www.java67.com/2017/08/difference-between-abstract-class-and-interface-in-java8.html))
-   20 Examples of Date and Time in Java 8 ([tutorial](https://javarevisited.blogspot.com/2015/03/20-examples-of-date-and-time-api-from-Java8.html))
-   How to sort the map by keys in Java 8? ([example](http://javarevisited.blogspot.sg/2017/07/how-to-sort-map-by-keys-in-java-8.html#axzz4pXFCC65F))
-   15 Java Stream and Functional Programming interview questions ([list](https://www.java67.com/2018/10/java-8-stream-and-functional-programming-interview-questions-answers.html))
-   How to convert List to Map in Java 8 ([solution](http://javarevisited.blogspot.com/2016/04/10-examples-of-converting-list-to-map.html))
-   10 examples of Optionals in Java 8? ([example](http://javarevisited.blogspot.sg/2017/04/10-examples-of-optional-in-java-8.html#axzz4pXFCC65F))

Thanks for reading this article so far. If you find this Java tutorial useful then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note.


P.S.-  If you are serious about improving your functional programming skills in Java and wan to learn more about Java Stream API, I strongly recommend you to checkout [**Learn Java Functional Programming with Lambdas & Streams**](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Ffunctional-programming-with-java%2F) course by Ranga Rao Karnam on Udemy, which explains Stream fundamentals in good detail.