Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max on BigDecimal list using java 8

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 ?

like image 440
Grechka Vassili Avatar asked Aug 04 '17 11:08

Grechka Vassili


1 Answers

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.

like image 161
Peter Lawrey Avatar answered Sep 26 '22 06:09

Peter Lawrey