IntStream filter() method in Java


The filter() method of the IntStream class in Java returns a stream consisting of the elements of this stream that match the given predicate.

The syntax is as follows −

IntStream filter(IntPredicate predicate)

Here, the predicate parameter is a stateless predicate to apply to each element to determine if it should be included. The IntPredicate above is the predicate of one int-valued argument.

Create an IntStream and add elements −

IntStream intStream = IntStream.of(20, 34, 45, 67, 89, 100);

Now, set a condition and filter stream elements based on it using the filter() method −

intStream.filter(a -> a < 50).

The following is an example to implement IntStream filter() method in Java −

Example

 Live Demo

import java.util.*;
import java.util.stream.IntStream;

public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(20, 34, 45, 67, 89, 100);
      System.out.println("The following elements matches the given predicate:");
      intStream.filter(a -> a < 50).forEach(System.out::println);
   }
}

Output

The following elements matches the given predicate:
20
34
45

Updated on: 30-Jul-2019

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements