Introduction
Java 8 introduced lambda expressions and the Stream API, which provide a powerful and concise way to handle collections of data. One of the most common tasks when working with collections is filtering data based on specific criteria. Before Java 8, filtering a list of objects required writing loops or using third-party libraries. With lambda expressions and the Stream API, filtering lists has become more straightforward and expressive.
In this blog post, we’ll explore how to filter a list of objects using lambda expressions in Java 8.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Filtering a List of Custom Objects
- Advanced Considerations
- Conclusion
Problem Statement
When working with lists of objects, you often need to filter the list based on certain attributes or criteria. The task is to create a Java program that filters a list of custom objects using lambda expressions, returning only those objects that meet the specified conditions.
Example:
- Input: A list of
Product
objects, each with attributes such asname
andprice
. - Output: A filtered list containing only the
Product
objects where theprice
is greater than $500.
Solution Steps
- Create a
Product
Class: Define aProduct
class with attributes such asname
andprice
. - Create a List of
Product
Objects: Define a list ofProduct
objects. - Use the Stream API: Utilize the
filter()
method in conjunction with a lambda expression to filter the list based on the desired criteria. - Collect the Results: Use
Collectors.toList()
to collect the filtered objects back into a list.
Java Program
Filtering a List of Custom Objects
Below is an example that demonstrates how to filter a list of Product
objects using lambda expressions.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8 - Filter a List of Objects with Lambda Expressions
* Author: https://www.rameshfadatare.com/
*/
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return name + " ($" + price + ")";
}
}
public class FilterListWithLambda {
public static void main(String[] args) {
// Step 1: Create a list of Product objects
List<Product> products = new ArrayList<>();
products.add(new Product("Laptop", 1200.00));
products.add(new Product("Smartphone", 800.00));
products.add(new Product("Tablet", 300.00));
products.add(new Product("Smartwatch", 150.00));
products.add(new Product("Headphones", 100.00));
// Step 2: Filter the list by price using the Stream API and a lambda expression
List<Product> filteredProducts = products.stream()
.filter(product -> product.getPrice() > 500)
.collect(Collectors.toList());
// Step 3: Display the filtered list
filteredProducts.forEach(product ->
System.out.println("Product: " + product));
}
}
Output
Product: Laptop ($1200.0)
Product: Smartphone ($800.0)
Explanation
- Product Class: The
Product
class has two attributes,name
andprice
, with corresponding getter methods and atoString()
method for easy display. - Filtering by Price: The
filter(product -> product.getPrice() > 500)
lambda expression filters the products to include only those with a price greater than $500. - Collecting Results: The
Collectors.toList()
method collects the filteredProduct
objects into a new list,filteredProducts
. - Displaying the Results: The
forEach()
method is used to iterate over and print each product in the filtered list.
Advanced Considerations
-
Multiple Criteria: You can filter the list based on multiple criteria by chaining additional
filter()
methods. For example, you might filter by both price and name:List<Product> filteredProducts = products.stream() .filter(product -> product.getPrice() > 500) .filter(product -> product.getName().startsWith("S")) .collect(Collectors.toList());
-
Custom Comparators: If you need to sort the filtered list as well, you can chain the
sorted()
method with a custom comparator:List<Product> sortedFilteredProducts = products.stream() .filter(product -> product.getPrice() > 500) .sorted(Comparator.comparing(Product::getPrice)) .collect(Collectors.toList());
-
Handling Empty Results: Ensure that your code handles cases where the filtered list may be empty, depending on your application’s requirements.
Conclusion
This blog post demonstrated how to filter a list of objects using lambda expressions and the Stream API in Java 8. By leveraging these powerful features, you can efficiently filter and process lists of custom objects, making your code more concise and easier to maintain. Whether you’re filtering based on a single criterion or multiple conditions, the Stream API combined with lambda expressions provides a flexible and powerful solution for working with collections in Java.