Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

IntStream filter() in Java with examples

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

IntStream filter(IntPredicate 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 :

IntStream filter(IntPredicate predicate)

Where, IntStream is a sequence of primitive int-valued elements.
IntPredicate represents a predicate (boolean-valued function) 
of one int-valued argument and the function returns the new stream.

Example 1 : filter() method on IntStream.




// Java code for IntStream filter
// (IntPredicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an IntStream
        IntStream stream = IntStream.of(3, 5, 6, 8, 9);
  
        // Using IntStream filter(IntPredicate predicate)
        // to get a stream consisting of the
        // elements that gives remainder 2 when
        // divided by 3
        stream.filter(num -> num % 3 == 2)
            .forEach(System.out::println);
    }
}

Output :

5
8

Example 2 : filter() method on IntStream.




// Java code for IntStream filter
// (IntPredicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an IntStream
        IntStream stream = IntStream.of(-2, -1, 0, 1, 2);
  
        // Using IntStream filter(IntPredicate predicate)
        // to get a stream consisting of the
        // elements that are greater than 0
        stream.filter(num -> num > 0)
            .forEach(System.out::println);
    }
}

Output :

1
2

My Personal Notes arrow_drop_up
Last Updated : 06 Dec, 2018
Like Article
Save Article
Similar Reads
Related Tutorials