I want to use java streams to iterate a list and find the BigDecimal
minimum price. The following illustrates, but does not work (because min()
cannot accept BigDecimal
.
class Product {
public BigDecimal price;
}
List<Product> products;
products.stream().min((Product) p -> p.price);
min method we get the minimum element of this stream for the given comparator. Using Stream. max method we get the maximum element of this stream for the given comparator. The min and max method both are stream terminal operations.
A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
2. Using Stream. max() method. The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator .
Since BigDecimal
already is Comparable
, it is as simple as :
BigDecimal min = products
.stream()
.map(Product::getPrice)
.min(Comparator.naturalOrder())
.orElse(BigDecimal.ZERO);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With