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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With