Stream filter() in Java with examples
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
Last Updated :
03 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...