Consider a class User
public class User{
int userId;
String name;
Date date;
}
Now I have a List
You should not call .get() directly. Optional<>, that Stream::max
returns, was designed to benefit from .orElse... inline handling.
If you are sure your arguments have their size of 20:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElseThrow(() -> new IllegalArgumentException("Expected a list of size: 20. Was: 0"));
If you support empty lists, then return some default value, for example:
list.stream()
.map(u -> u.date)
.max(Date::compareTo)
.orElse(new Date(Long.MIN_VALUE));
CREDITS to: @JimmyGeers, @assylias from the accepted answer.