注:转载请注明出处!!!

这里直接用取出多个对象中某个值 最大/最小 来进行举例

直接看代码

 /**
* 时间测试类
*/
class TimeTest {
private Date time; public Date getTime() {
return time;
} public void setTime(Date time) {
this.time = time;
}
}

工具类:

 public class DateUtils extends org.apache.commons.lang.time.DateUtils{
//自定义日期格式
public static final String SIMPLE_DATEFORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String SIMPLE_DATEFORMAT_YMD = "yyyy-MM-dd";
//日期比较方法
public static int compareDate(Date first, Date second){
return first.compareTo(second);
}
//日期转string
public static String formatDateYMDHMS(Date date){
if(date==null){
return null;
}
return format(date,SIMPLE_DATEFORMAT);
}
//通用格式化
public static String format(Date date, String pattern) {
if (date == null) {
return null;
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
}

运行:

 public static void main(String[] args) {
int i = 0;
List<TimeTest> timeList = new ArrayList<>();
while (++i <= 5) {
TimeTest time = new TimeTest();
time.setTime(DateUtils.addMonths(DateUtils.now(), i));
timeList.add(time);
}
//插入一个空值
TimeTest time = new TimeTest();
timeList.add(time);
System.out.println("---------------初始值------------------");
timeList.forEach(o -> {
System.out.println(DateUtils.formatDateYMDHMS(o.getTime()));
});
System.out.println("---------------------------------------");
//下面有两种写法 推荐使用方法一
//代码解释: 将timeList流首先过滤时间不为空的,将需要比较的值转出map然后去重,最后取出最大值/最小值
//方法一 min(DateUtils::compareDate) 这种写法需要自己写工具类,且compareDate必须是static修饰
Date min = timeList.stream().filter(o -> o.getTime() != null).map(TimeTest::getTime).distinct().min(DateUtils::compareDate).get();
//方法二 max((e1, e2) -> e1.compareTo(e2))这种写法需要类里面含有比较方法
Date max = timeList.stream().filter(o -> o.getTime() != null).map(TimeTest::getTime).distinct().max((e1, e2) -> e1.compareTo(e2)).get();
System.out.println("min=" + DateUtils.formatDateYMDHMS(min));
System.out.println("max=" + DateUtils.formatDateYMDHMS(max));
}

输出:

 ---------------初始值------------------
2019-09-09 14:35:53
2019-10-09 14:35:53
2019-11-09 14:35:53
2019-12-09 14:35:53
2020-01-09 14:35:53
null
---------------------------------------
min=2019-09-09 14:35:53
max=2020-01-09 14:35:53 Process finished with exit code 0
05-08 08:27