Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
Where Stream is an interface and T is the type of the input to the predicate.
Return Type: A new stream.
Implementation:
- Filtering out the elements divisible by some specific number ranging between 0 to 10.
- Filtering out the elements with an upperCase letter at any specific index.
- Filtering out the elements ending with custom alphabetical letters.
Example 1: filter() method with the operation of filtering out the elements divisible by 5.
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
List<Integer> list = Arrays.asList( 3 , 4 , 6 , 12 , 20 );
list.stream()
.filter(num -> num % 5 == 0 )
.forEach(System.out::println);
}
}
|
Example 2: filter() method with the operation of filtering out the elements with an upperCase letter at index 1.
Java
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> stream = Stream.of(
"Geeks" , "fOr" , "GEEKSQUIZ" , "GeeksforGeeks" );
stream
.filter(
str -> Character.isUpperCase(str.charAt( 1 )))
.forEach(System.out::println);
}
}
|
Example 3: filter() method with the operation of filtering out the elements ending with custom alphabetically letter say it be ‘s’ for implementation purposes.
Java
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream<String> stream = Stream.of(
"Geeks" , "foR" , "GeEksQuiz" , "GeeksforGeeks" );
stream.filter(str -> str.endsWith( "s" ))
.forEach(System.out::println);
}
}
|
Output
Geeks
GeeksforGeeks
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
03 May, 2022
Like Article
Save Article