Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find minimum of BigDecimal field in collection with java streams?

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);
like image 226
membersound Avatar asked Dec 08 '17 10:12

membersound


People also ask

How do you use max and min in stream?

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.

What is the range of BigDecimal in Java?

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.

How will you get the highest number present in a list using Java 8?

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 .


1 Answers

Since BigDecimal already is Comparable, it is as simple as :

 BigDecimal min = products
        .stream()
        .map(Product::getPrice)
        .min(Comparator.naturalOrder())
        .orElse(BigDecimal.ZERO);
like image 108
Eugene Avatar answered Sep 20 '22 05:09

Eugene