How do I find the smallest BigDecimal field in a collection using a Java stream?

I want to use the Java stream to iterate over the list and find the lowest price for BigDecimal The following instructions do not work (because min() does not accept BigDecimal

class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);

Solution

Since BigDecimal is already comparable, it is very simple:

BigDecimal min = products
        .stream()
        .map(Product::getPrice)
        .min(Comparator.naturalOrder())
        .orElse(BigDecimal.ZERO);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>