Beispiel: Filtern Sie eine Liste von Produkten, deren Preis auf fromPrice und toPrice basiert. Sie könnten entweder beide geliefert werden, oder nur einer.Java 8: Stream und Filter basierend auf optionalen Bedingungen
- aller Produkte, deren Preis größer als fromPrice
- aller Produkte, deren Preis weniger als toPrice
- aller Produkte, deren Preis zwischen fromPrice und toPrice
Produkt:
public class Product {
private String id;
private Optional<BigDecimal> price;
public Product(String id, BigDecimal price) {
this.id = id;
this.price = Optional.ofNullable(price);
}
}
PricePredicate:
public class PricePredicate {
public static Predicate<? super Product> isBetween(BigDecimal fromPrice, BigDecimal toPrice) {
if (fromPrice != null && toPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0 &&
product.getPrice().get().compareTo(toPrice) <= 0;
}
if (fromPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(fromPrice) >= 0;
}
if (toPrice != null) {
return product -> product.getPrice().isPresent() && product.getPrice().get().compareTo(toPrice) <= 0;
}
return null;
}
}
Filter:
return this.products.stream().filter(PricePredicate.isBetween(fromPrice, null)).collect(Collectors.toList());
return this.products.stream().filter(PricePredicate.isBetween(null, toPrice)).collect(Collectors.toList());
return this.products.stream().filter(PricePredicate.isBetween(fromPrice, toPrice)).collect(Collectors.toList());
Gibt es eine Möglichkeit, mein Prädikat statt mit dem, wenn nicht null Kontrollen zu verbessern? Alles, was mit Optionals möglich ist?
Der erste Satz ist genug, um ein +1 von mir zu verdienen. – Jubobs
Danke. Das sieht gut aus. aber ich bekomme einen Kompilierfehler hier: Optional price = product.getPrice(); kann Symbol "Produkt" nicht auflösen –
Oh ja, sorry, mein Code macht keinen Sinn. Lass es mich reparieren. –