This tutorial will show you how to use Java 8 stream API’s filter and map methods.

filter() method 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.

Example

package com.roytuts.java8.stream;

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

public class FilterExample {

	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' and '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));
                
                //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);

                //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);
	}

}

Output

roytuts
soumitra
roytuts
roytuts

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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