Java Stream filter() Example

The Java Stream filter() is an intermediate operation.

Java Stream filter() Example 1

The Java Stream filter() can be used to filter out elements from a Java Stream. The filter method takes a Predicate that is called for each element in the stream. If the element is to be included in the resulting Stream, the Predicate should return true. If the element should not be included, the Predicate should return false.


Here is an example of calling the Java Stream filter() method:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Tester {
   public static void main(String[] args){
        List<String> lines = Arrays.asList("java", "c", "python");

        List<String> result = lines.stream()       // convert list to stream
                .filter(line -> !"c".equals(line)) // we dont like c
                .collect(Collectors.toList());     // collect the output and convert streams to a List

        result.forEach(System.out::println);  
    }
}

Output:

java
python

Using filter() method to filter List of string objects:

Java Stream filter() Example 2

In this example, we will create a list of products and we filter products whose price is greater than 25k. We display a list of products using the forEach() method.
Let's first create a Product class:
class Product {
    private int id;
    private String name;
    private float price;
   // getters and setters 
}
public class StreamFilterExample {
    public static void main(String[] args) {

        // using stream API
        List < Product > filteredProducts = getProducts().stream()
            .filter((product) -> product.getPrice() > 25000 f)
            .collect(Collectors.toList());
        filteredProducts.forEach(System.out::println);
    }

    private static List < Product > getProducts() {
        List < Product > productsList = new ArrayList < Product > ();
        productsList.add(new Product(1, "HP Laptop", 25000 f));
        productsList.add(new Product(2, "Dell Laptop", 30000 f));
        productsList.add(new Product(3, "Lenevo Laptop", 28000 f));
        productsList.add(new Product(4, "Sony Laptop", 28000 f));
        productsList.add(new Product(5, "Apple Laptop", 90000 f));
        return productsList;
    }
}
In the above example, we are using the filter() method to filter products whose price is greater than 25k:
       List < Product > filteredProducts = getProducts().stream()
            .filter((product) -> product.getPrice() > 25000 f)
            .collect(Collectors.toList());

Java Stream Methods/APIs Examples


Comments