LongStream filter() in Java with examples

LongStream filter(LongPredicate 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 :

LongStream filter(LongPredicate predicate)

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

Example 1 : filter() method on LongStream.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for LongStream filter
// (LongPredicate predicate) to get a stream
// consisting of the elements of this
// stream that match the given predicate.
import java.util.*;
import java.util.stream.LongStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating an LongStream
        LongStream stream = LongStream.of(3L, 5L, 6L, 8L, 9L);
  
        // Using LongStream filter(LongPredicate 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);
    }
}

chevron_right


Output :

5
8

Example 2 : filter() method on LongStream.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

1
2


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.