How to find Max Date in List<Object>?

前端 未结 6 2189
被撕碎了的回忆
被撕碎了的回忆 2020-12-23 19:13

Consider a class User

public class User{
  int userId;
  String name;
  Date date;
}

Now I have a List

6条回答
  •  隐瞒了意图╮
    2020-12-23 19:27

    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.

提交回复
热议问题