Java 8 Stream Filter Example

This tutorial will show you how to use Java 8 stream API’s filter and map methods. The filter() method in Java 8 or onward is used to produce a stream containing only a certain type of objects into the result output and map() method is used to transform a stream from one type to another type into the result output.


At least Java 8


We will create a main class and apply filter() method various ways with examples.

We define a list of string values on which we will apply filter() method in different ways.

The first filter() method checks if the string is equal to roytuts or soumitra then build a result list with these values. So it outputs roytuts and soumitra.

Next we are returning any string based on roytuts. So it outputs soumitra which is any string from the list. If desired value is not found then it will return null.

Next if the found value is compatible with string then transform it into string and return otherwise return null. So it outputs roytuts.


import java.util.Arrays;
import java.util.List;

public class JavaStreamFilter {

	public static void main(String[] args) {
		// define a list of string values
		List<String> list = Arrays.asList("roytuts", "soumitra", "abc", "java", "bekar");

		// produce a result list which has only 'roytuts' or 'soumitra'
		// first filter the values
		// second collect again those values into a list
		List<String> resultList = -> "roytuts".equals(s) || "soumitra".equals(s))

		resultList.forEach(s -> System.out.println(s));

		// find any value in the list of string using findAny() and if the desired value
		// is not found then return null
		String findAny = -> "roytuts".equals(s)).findAny().orElse(null);


		// transform the found value into string if it is compatible
		String mapToString = -> "roytuts".equals(s)).map(String::toString).findAny()



Testing the Program

When you run the above program you will see below output in the console:


Source Code

You can download source code.

Thanks for reading.

Leave a Comment