Java 8 Filter
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.
The filter()
method of Java stream API is an intermediate operation that reads data from a stream and returns a new stream after transforming data based on the given condition. Filter allows you to filter elements of a stream that match a given Predicate. So filter()
is an example of Predicate.
So filter returns a stream consisting of the elements of this stream that match the given predicate.
The signature of filter()
method in Java’s Stream interface is given below:
Stream<T> filter(Predicate<? super T> predicate)
The filter()
returns a stream consisting of the elements of this stream that match the given predicate.
Prerequisites
Java 8+
Java 8 Stream’s Filter Example
I will create a main class and apply filter()
method various ways with examples.
I define a list of string values on which I 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 I am 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
.
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 Filter Example
When you run the above program you will see below output in the console:
roytuts
soumitra
---
roytuts
---
roytuts