Find max on BigDecimal list using java 8

Grechka Vassili :

Let's suppose that I have a class like this :

public class A {
    private int id;
    private BigDecimal amount;
}

And I have a List<A>. How can I find the maximum amount of all A objects in the list using Java 8 stream ?

This method :

List<A> brol = new ArrayList<>();
BigDecimal max = brol.stream().max(Comparator.comparing(A -> A.getAmount())).get().getAmount();
        System.out.println("MAX = " + max);

Gives NoSuchElementException so I should create a specific comparator for this ?

Peter Lawrey :

What I would do is check the Optional

Optional<BigDecimal> max = brol.stream()
                               .map(a -> a.amount)
                               .max(Comparator.naturalOrder());
if (max.isPresent()) {
   // have a max
}

Instead of the Comparator.naturalOrder(), you can use BigDecimal::compare if you feel this is clearer.

The Optional.get() is throwing the NoSuchElementException as there is no element. You only need to provide a Comparator when the Object you are getting the max is not Comparable

In this case, you don't need the maximum A only the maximum amount which is a BigDecimal which is Comparable.

You could provide a comparator if you actually wanted the minimum though using min() would be a simpler choice in this regard.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471023&siteId=1