I defined a Product
class like this:
public class Product {
String name;
ProductType type;
BigDecimal price;
// Getters and Setters omitted
}
With the ProductType
as an enum
class:
public enum ProductType {
APPLE, PEAR, BANANA
}
Now I have created a List<Product>
where I added all kinds of products. What I would like to do is to be able to sort this list on price and filter it on type.
What are the standard ways to implement this kind of behavior?
In Java 8:
List<Product> products = // ...
List<Product> filterSortedProdycts =
products.stream()
.filter(p -> p.getType() == ProductType.BANANA) // only keep BANANA
.sorted(Comparator.comparing(Product::getPrice)) // sort by price
.collect(Collectors.toList());