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.

Prerequisites

At least Java 8

Example

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.

package com.roytuts.java.stream.filter.example;

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

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 = list.stream().filter(s -> "roytuts".equals(s) || "soumitra".equals(s))
				.collect(Collectors.toList());

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

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

		System.out.println(findAny);
		System.out.println("---");

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

		System.out.println(mapToString);
	}

}

Testing the Program

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

roytuts
soumitra
---
roytuts
---
roytuts

Source Code

You can download source code.

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *