Java Stream Filter List of Objects



In this source code example, we will show you how to filter User-defined class objects using Java 8 Stream API.

Java Stream Filter List of Objects

Let's create a user-defined class Product:
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 + "]";
    }
}
Now lets write a logic to filter products based on price using Java 8 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() > 25000f)
            .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]

Comments