Let’s say you have a list of Product
objects, and you want to perform different operations on these products based on certain conditions. You might want to apply one operation to products that meet specific criteria and a different operation to those that don’t. Using a Consumer
, you can encapsulate these different operations and easily apply them as needed.
Here’s an example:
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
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;
}
}
public class Main {
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Laptop", 1000),
new Product("Phone", 700),
new Product("Tablet", 500)
);
// Define different consumers for different operations
Consumer<Product> discountConsumer = product -> {
double discountedPrice = product.getPrice() * 0.9; // Apply 10% discount
System.out.println("Applying discount to " + product.getName() + ": $" + discountedPrice);
};
Consumer<Product> normalPriceConsumer = product -> {
System.out.println("No discount applied to " + product.getName() + ": $" + product.getPrice());
};
// Apply different operations based on product price
products.forEach(product -> {
if (product.getPrice() > 800) {
discountConsumer.accept(product); // Apply discount for expensive products
} else {
normalPriceConsumer.accept(product); // Keep normal price for other products
}
});
}
}
In this example:
- We define two different
Consumer
instances:discountConsumer
andnormalPriceConsumer
, each representing a different operation to be performed onProduct
objects. - We use a lambda expression to specify what each
Consumer
does. - Within the
forEach
loop, we check each product’s price and apply the appropriateConsumer
to it based on the condition (in this case, whether the price is greater than $800). - Using
accept()
, we execute the appropriateConsumer
for each product.
This approach allows for better organization of code, as each operation is encapsulated within its own Consumer
. It also offers flexibility, as you can easily add or modify operations without changing the iteration logic.