Introduction
Java 8 introduced lambda expressions and the Stream API, which provide powerful and concise ways to manipulate collections and maps. One common use case is filtering a map based on its keys. This can be particularly useful when you need to extract a subset of entries from a map that meet specific criteria. In this guide, we’ll explore how to filter a map by its keys using lambda expressions, with a focus on a map containing custom objects, specifically a Product class.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Filtering a Map by Key
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Filters a map of
Productobjects by their keys using a lambda expression. - The map’s keys are product IDs, and the
Productobjects contain details like name and price.
Example:
- Input: A map with product IDs as keys and
Productobjects as values. - Output: A filtered map containing only the entries where the key matches a specific condition.
Solution Steps
- Create a
ProductClass: Define aProductclass with attributes likenameandprice. - Create a Map of
ProductObjects: Define a map with product IDs as keys andProductobjects as values. - Use the
filter()Method: Utilize theStreamAPI to filter the map based on the keys using a lambda expression. - Collect the Results: Use
Collectors.toMap()to collect the filtered results back into a map.
Java Program
Filtering a Map by Key
Let’s assume we have a Product class with name and price attributes.
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
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 FilterMapByKey {
public static void main(String[] args) {
// Step 1: Create a Map of Product objects with product IDs as keys
Map<Integer, Product> productMap = new HashMap<>();
productMap.put(1, new Product("Laptop", 1200.00));
productMap.put(2, new Product("Smartphone", 800.00));
productMap.put(3, new Product("Tablet", 300.00));
productMap.put(4, new Product("Smartwatch", 150.00));
productMap.put(5, new Product("Headphones", 100.00));
// Step 2: Filter the map by keys using a lambda expression
// Example: Filter out products with keys less than 3
Map<Integer, Product> filteredMap = productMap.entrySet()
.stream()
.filter(entry -> entry.getKey() >= 3)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Step 3: Display the filtered map
filteredMap.forEach((key, product) ->
System.out.println("Product ID: " + key + ", Product: " + product));
}
}
Output
Product ID: 3, Product: Tablet ($300.0)
Product ID: 4, Product: Smartwatch ($150.0)
Product ID: 5, Product: Headphones ($100.0)
Explanation
- Product Class: The
Productclass has two attributes,nameandprice, along with getter methods and atoString()method for easy display. - Map Creation: We create a
Map<Integer, Product>where the keys are product IDs and the values areProductobjects. - Filtering by Key: The
filter()method filters the map entries based on the key. In this example, we keep only those entries where the key is greater than or equal to 3. - Collecting Results: The
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))method collects the filtered entries back into a new map. - Displaying the Map: The filtered map is printed out, showing only the products with IDs 3, 4, and 5.
Advanced Considerations
-
Custom Conditions: You can customize the filtering condition in the lambda expression based on specific business logic, such as filtering keys based on ranges, specific values, or even patterns.
-
Null Handling: Ensure that your filtering logic accounts for potential
nullkeys or values in the map, especially if the map can contain null entries. -
Immutable Results: If you need the filtered map to be immutable, consider wrapping the result in
Collections.unmodifiableMap().
Conclusion
This guide demonstrates how to filter a map by its keys using lambda expressions in Java 8, focusing on a map containing custom objects like Product. By leveraging the Stream API and lambda expressions, you can efficiently filter and manipulate collections, making your code more concise and expressive. Whether you’re filtering simple data or working with complex objects, Java 8 provides the tools to handle these tasks with ease and flexibility.