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
// Java code for Stream filter // (Predicate predicate) to get a stream // consisting of the elements of this // stream that match the given predicate. import java.io.*; import java.util.stream.Stream; class StreamFilterExample { public static void main(String[] args) { // create a stream of strings Stream<String> myStream = Stream.of( "Like" , "and" , "Share" , // only string starting with "http://" will be // considered for next API(forEach) .forEach(System.out::println); } } |
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
// Java program to demonstrate // filter by Object properties import java.io.*; import java.util.stream.Stream; class FilterByObjectProperties { public static void filterByEvenElements() { // create integer array Integer[] myArray = new Integer[] { 1 , 4 , 5 , 7 , 9 , 10 }; // create a stream and filter by // even numbers predicate Stream.of(myArray) .filter(x -> x % 2 == 0 ) .forEach(System.out::println); } public static void filterByStartsWith() { // create String array String[] myArray = new String[] { "stream" , "is" , "a" , "sequence" , "of" , "elements" , "like" , "list" }; // create a stream and filter by // starting string predicate Stream<String> myStream = Stream.of(myArray); myStream.filter(x -> x.startsWith( "s" )) .forEach(System.out::println); } public static void filterByStartsWithVowelsRegex() { // create string array String[] myArray = "I am 24 years old and I want to be in Tier I company" .split( " " ); // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // filter by matching vowels regular expression myStream.filter(x -> x.matches( "(a|e|i|o|u)\\w*" )) .forEach(System.out::println); } public static void main(String[] args) { // filters a stream by even elements filterByEvenElements(); System.out.println( "======" ); // filters a stream by starting string filterByStartsWith(); System.out.println( "======" ); // filters a stream by starting vowel filterByStartsWithVowelsRegex(); } } |
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
// Java program to demonstrate // filter by Object Indices // using AtomicInteger import java.io.*; import java.util.stream.Stream; import java.util.concurrent.atomic.AtomicInteger; class FilterByObjectIndex { public static void filterByIndexUsingAtomic() { // create a string array String[] myArray = new String[] { "stream" , "is" , "a" , "sequence" , "of" , "elements" , "like" , "list" }; // create a stream on myArray Stream<String> myStream = Stream.of(myArray); // create an AtomicInteger AtomicInteger i = new AtomicInteger( 0 ); // increment the i value by 1 everytime // if it is even, print the current element myStream.filter(x -> i.getAndIncrement() % 2 == 0 ) .forEach(System.out::println); } public static void main(String[] args) { // filter by Object index filterByIndexUsingAtomic(); } } |
stream a of like
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
// Java program to demonstrate // filter by Object properties // using IntSteam Approach import java.io.*; import java.util.stream.IntStream; class FilterByObjectIndexUsingIntStream { public static void filterByIndexUsingStream() { // create an array of Strings String[] myArray = new String[] { "stream" , "is" , "a" , "sequence" , "of" , "elements" , "like" , "list" }; // create instream on range of integers // filter by even integer and map // the integer to the Object of myArray 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(); } } |
stream a of like
Filter by Custom Properties
We can use any Java Object property for filtering. Here we are filtering by age.
Java
// Java program to demonstrate // filter by Custom Properties import java.io.*; import java.util.List; import java.util.Arrays; import java.util.stream.Stream; class CustomFiltering { // Employee class class Employee { // attributes of an Employee String name; int age; // constructor Employee(String name, int age) { this .name = name; this .age = age; } // Override toString to print // provided content when an Object // is printed @Override public String toString() { return "Employee [name=" + name + "]" ; } } public static void filterByAge() { // create list of Employees List<Employee> myList = Arrays.asList( new GFG(). new Employee( "Ram" , 25 ), new GFG(). new Employee( "Kumar" , 40 ), new GFG(). new Employee( "Rakesh" , 35 )); // create a stream on the list // filter by age of an employee myList.stream() .filter(x -> x.age >= 35 ) .forEach(System.out::println); } public static void main(String[] args) { filterByAge(); } } |
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
// Java program to demonstrate // Custom filter import java.io.*; import java.util.stream.Stream; class CustomFilterExample { public static void filterByCustomProperties() { // create a string array String[] myArray = new String[] { "madam" , "please" , "refer" , "link" , "on" , "racecar" }; // filter using a custom method Stream.of(myArray) .filter(x -> palindrome(x)) .forEach(System.out::println); } // checks if palindrome or not 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(); } } |
madam refer racecar