Java 8 Stream - filter() and forEach() Example

In this tutorial, we will learn how to use Stream.filter() and Stream.forEach() method with an example.
Java stream provides a filter() method to filter stream elements on the basis of a given predicate. This method takes a predicate as an argument and returns a stream consisting of resulted elements.
Learn Stream API at https://www.javaguides.net/p/java-8-stream-api-tutorial.html
Check out Stream API for beginners at https://www.javaguides.net/2020/04/java-8-stream-tutorial-for-beginners.html 

Video Tutorial

This tutorial explained in below youtube video:

1. Stream API Overview

A stream represents a sequence of objects from a source, which supports aggregate operations.
Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces, and an enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package in your programs.
Learn more about Streams at https://www.javaguides.net/p/java-8-stream-api-tutorial.html

2. Java 8 Stream - filter() and forEach() Example

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;

    public Product(int id, String name, float price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
}

Without Stream API - Traditional Way

First, we will see how we filter in a traditional way ( without using stream API):
import java.util.ArrayList;
import java.util.List;

/**
 * Stream filter and forEach() method example
 * @author Ramesh Fadatare
 *
 */
public class StreamFilterExample {
    public static void main(String[] args) {

        // traditional way
        List < Product > list = new ArrayList < Product > ();

        for (Product product: getProducts()) {
            if (product.getPrice() > 25000 f) {
                list.add(product);
            }
        }

        for (Product product: list) {
            System.out.println(product);
        }
    }

    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;
    }
}
Output:
Product [id=2, name=Dell Laptop, price=30000.0]
Product [id=3, name=Lenevo Laptop, price=28000.0]
Product [id=4, name=Sony Laptop, price=28000.0]
Product [id=5, name=Apple Laptop, price=90000.0]

Using Stream API

import java.util.ArrayList;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Stream filter and forEach() method example
 * 
 * @author Ramesh Fadatare
 *
 */
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;
    }
}
Output:
Product [id=2, name=Dell Laptop, price=30000.0]
Product [id=3, name=Lenevo Laptop, price=28000.0]
Product [id=4, name=Sony Laptop, price=28000.0]
Product [id=5, name=Apple Laptop, price=90000.0]
We can use forEach() method directly on stream() like:
getProducts().stream()
.filter((product) -> product.getPrice() > 25000f)
.forEach(System.out::println);
Learn and master in Java 8 features at Java 8 Tutorial with Examples

Comments