Java 8 filters

Stream filter(Predicate predicate) provides a stream that contains the elements of this stream that satisfy the supplied predicate. This is a step-by-step procedure. These actions are always lazy, which means that calling filter() does not really filter anything, but instead creates a new stream that contains the items of the original stream that fit the provided predicate when browsed.

Syntax

Java Stream filter() Example 1

In this example, we use the stream() function to create a stream from a list of countrynames, and then we use the stream filter method to create another stream of longcountrynames. The stream filter, as previously said, turns data from one stream into data from another stream.

StreamFilterExample1.java

Output:

America Ireland Finland

Java Stream filter() with multiple conditions Example 2

In the below code, we can see that the filter() method only has one criterion. We can use the logical operators in Java to unite multiple conditions in the filter() method. Two conditions in the filter method are linked using the (&&) logical operator in the following example.

StreamFilterExample2.java

Output:

India

Java Stream filter() and map() Example 3

In the following Java code, the stream filter() is used along with map() method to print squares of given numbers.

StreamFilterExample3.java

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Java Stream filter() and collect() Example 4

In the following Java code, the stream filter() is used along with collect() method.

StreamFilterExample4.java

Output:

America
Canada
Ireland
India

Java Stream filter() with min() and max() Example 4

In the following Java code, the stream filter() is used along with the min() and max() method to find out the minimum and maximum number from the given list of numbers.

StreamFilterExample5.java

Output:

Min value: 1
Max value: 5





Latest Courses