Java Stream API – Filters
In this article, we will learn Java Stream Filter API. We will cover,
1. How stream filter API works.
2. Filter by Object Properties.
3. Filter by Index.
4. Filter by custom Object properties.
Stream Filter API
Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argument of any type and returns Boolean. The element will be considered for the next API in the pipeline if the function returns true. Otherwise, the element is filtered out.
Java
import java.io.*;
import java.util.stream.Stream;
class StreamFilterExample {
public static void main(String[] args)
{
Stream<String> myStream
= Stream.of( "Like" , "and" , "Share" ,
myStream.filter(x -> x.startsWith( "https://" ))
.forEach(System.out::println);
}
}
|
Output
https://www.geeksforgeeks.org/
Filter by Object Properties
Filter by Object properties uses java operators. The below example explains how to filter by properties of an object.
Java
import java.io.*;
import java.util.stream.Stream;
class FilterByObjectProperties {
public static void filterByEvenElements()
{
Integer[] myArray
= new Integer[] { 1 , 4 , 5 , 7 , 9 , 10 };
Stream.of(myArray)
.filter(x -> x % 2 == 0 )
.forEach(System.out::println);
}
public static void filterByStartsWith()
{
String[] myArray
= new String[] { "stream" , "is" , "a" ,
"sequence" , "of" , "elements" ,
"like" , "list" };
Stream<String> myStream = Stream.of(myArray);
myStream.filter(x -> x.startsWith( "s" ))
.forEach(System.out::println);
}
public static void filterByStartsWithVowelsRegex()
{
String[] myArray
= "I am 24 years old and I want to be in Tier I company"
.split( " " );
Stream<String> myStream = Stream.of(myArray);
myStream.filter(x -> x.matches( "(a|e|i|o|u)\\w*" ))
.forEach(System.out::println);
}
public static void main(String[] args)
{
filterByEvenElements();
System.out.println( "======" );
filterByStartsWith();
System.out.println( "======" );
filterByStartsWithVowelsRegex();
}
}
|
Output
4
10
======
stream
sequence
======
am
old
and
in
Filter by Object Indices
Filtering by indexes can be done in two ways.
1. Atomic Integers
We need to use AtomicInteger because predicates expect final variables as parameters. As long as filter function(Predicate) returns boolean we can use any expression. Here, getAndIncrement() method of AtomicInteger increments the current value by 1 and returns final int value.
Java
import java.io.*;
import java.util.stream.Stream;
import java.util.concurrent.atomic.AtomicInteger;
class FilterByObjectIndex {
public static void filterByIndexUsingAtomic()
{
String[] myArray
= new String[] { "stream" , "is" , "a" ,
"sequence" , "of" , "elements" ,
"like" , "list" };
Stream<String> myStream = Stream.of(myArray);
AtomicInteger i = new AtomicInteger( 0 );
myStream.filter(x -> i.getAndIncrement() % 2 == 0 )
.forEach(System.out::println);
}
public static void main(String[] args)
{
filterByIndexUsingAtomic();
}
}
|
2. Intstream Approach
We can use Intstream and map the array elements based on the index. Here first we create an Intstream of a range of numbers. Check if a number is even, then overwrite/map the integer with the array element.
Java
import java.io.*;
import java.util.stream.IntStream;
class FilterByObjectIndexUsingIntStream {
public static void filterByIndexUsingStream()
{
String[] myArray
= new String[] { "stream" , "is" , "a" ,
"sequence" , "of" , "elements" ,
"like" , "list" };
IntStream.rangeClosed( 0 , myArray.length - 1 )
.filter(x -> x % 2 == 0 )
.mapToObj(x -> myArray[x])
.forEach(System.out::println);
}
public static void main(String[] args)
{
filterByIndexUsingStream();
}
}
|
Filter by Custom Properties
We can use any Java Object property for filtering. Here we are filtering by age.
Java
import java.io.*;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Stream;
class CustomFiltering {
class Employee {
String name;
int age;
Employee(String name, int age)
{
this .name = name;
this .age = age;
}
@Override public String toString()
{
return "Employee [name=" + name + "]" ;
}
}
public static void filterByAge()
{
List<Employee> myList = Arrays.asList(
new GFG(). new Employee( "Ram" , 25 ),
new GFG(). new Employee( "Kumar" , 40 ),
new GFG(). new Employee( "Rakesh" , 35 ));
myList.stream()
.filter(x -> x.age >= 35 )
.forEach(System.out::println);
}
public static void main(String[] args)
{
filterByAge();
}
}
|
Output
Employee [name=Kumar]
Employee [name=Rakesh]
We can also create a custom function for filtering. The function must take a parameter and return a boolean value.
Java
import java.io.*;
import java.util.stream.Stream;
class CustomFilterExample {
public static void filterByCustomProperties()
{
String[] myArray
= new String[] { "madam" , "please" , "refer" ,
"link" , "on" , "racecar" };
Stream.of(myArray)
.filter(x -> palindrome(x))
.forEach(System.out::println);
}
public static boolean palindrome(String s)
{
if (s.length() <= 1 )
return true ;
else
return (s.charAt( 0 ) == s.charAt(s.length() - 1 ))
&& palindrome(
s.substring( 1 , s.length() - 1 ));
}
public static void main(String[] args)
{
filterByCustomProperties();
}
}
|
Output
madam
refer
racecar
Last Updated :
02 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...