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

青春壹個敷衍的年華 提交于 2020-07-03 03:34:08

问题


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);

回答1:


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

 BigDecimal min = products
        .stream()
        .map(Product::getPrice)
        .min(Comparator.naturalOrder())
        .orElse(BigDecimal.ZERO);



回答2:


You don't need a stream to find the minimum. Use Collections.min:

Collections.min(products, Comparator.comparing(p -> p.price));



回答3:


Did you try :

Product minProductPrice = producs.stream()
        .min((o1, o2) -> o1.price.compareTo(o2.price)).get();



回答4:


To solve this, please use the following code:

products.stream().min(Comparator.comparing(p -> p.price)).get();

Comparator.comparing method requires a Function that takes an input and returns a Comparable. This Comparable, in turn, is used by the comparing method to create a Comparator. The min method uses the Comparator to compare the elements in the stream. The lambda expression p->p.price creates a Function that takes an BigDecimal and returns an BigDecimal (which is a Comparable). Here, the lambda expression does not do much but in situations where you have a class that doesn't implement Comparable and you want to compare objects of that class using a property of that class that is Comparable, this is very useful. The call to get() is required because max(Comparator) return an Optional object.




回答5:


You can use the below as well,

BigDecimal bigDecimal = products.stream()
            .map(d -> d.getPrice())
            .reduce(BigDecimal::min).get();

System.out.println(bigDecimal.longValueExact());


来源:https://stackoverflow.com/questions/47712344/how-to-find-minimum-of-bigdecimal-field-in-collection-with-java-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!