java8 stream取出 最大值/最小值
注:转载请注明出处!!!
这里直接用取出多个对象中某个值 最大/最小 来进行举例
直接看代码
1 /** 2 * 时间测试类 3 */ 4 class TimeTest { 5 private Date time; 6 7 public Date getTime() { 8 return time; 9 } 10 11 public void setTime(Date time) { 12 this.time = time; 13 } 14 }
工具类:
1 public class DateUtils extends org.apache.commons.lang.time.DateUtils{ 2 //自定义日期格式 3 public static final String SIMPLE_DATEFORMAT = "yyyy-MM-dd HH:mm:ss"; 4 5 public static final String SIMPLE_DATEFORMAT_YMD = "yyyy-MM-dd"; 6 //日期比较方法 7 public static int compareDate(Date first, Date second){ 8 return first.compareTo(second); 9 } 10 //日期转string 11 public static String formatDateYMDHMS(Date date){ 12 if(date==null){ 13 return null; 14 } 15 return format(date,SIMPLE_DATEFORMAT); 16 } 17 //通用格式化 18 public static String format(Date date, String pattern) { 19 if (date == null) { 20 return null; 21 } 22 SimpleDateFormat format = new SimpleDateFormat(pattern); 23 return format.format(date); 24 } 25 }
运行:
1 public static void main(String[] args) { 2 int i = 0; 3 List<TimeTest> timeList = new ArrayList<>(); 4 while (++i <= 5) { 5 TimeTest time = new TimeTest(); 6 time.setTime(DateUtils.addMonths(DateUtils.now(), i)); 7 timeList.add(time); 8 } 9 //插入一个空值 10 TimeTest time = new TimeTest(); 11 timeList.add(time); 12 System.out.println("---------------初始值------------------"); 13 timeList.forEach(o -> { 14 System.out.println(DateUtils.formatDateYMDHMS(o.getTime())); 15 }); 16 System.out.println("---------------------------------------"); 17 //下面有两种写法 推荐使用方法一 18 //代码解释: 将timeList流首先过滤时间不为空的,将需要比较的值转出map然后去重,最后取出最大值/最小值 19 //方法一 min(DateUtils::compareDate) 这种写法需要自己写工具类,且compareDate必须是static修饰 20 Date min = timeList.stream().filter(o -> o.getTime() != null).map(TimeTest::getTime).distinct().min(DateUtils::compareDate).get(); 21 //方法二 max((e1, e2) -> e1.compareTo(e2))这种写法需要类里面含有比较方法 22 Date max = timeList.stream().filter(o -> o.getTime() != null).map(TimeTest::getTime).distinct().max((e1, e2) -> e1.compareTo(e2)).get(); 23 System.out.println("min=" + DateUtils.formatDateYMDHMS(min)); 24 System.out.println("max=" + DateUtils.formatDateYMDHMS(max)); 25 }
输出:
1 ---------------初始值------------------ 2 2019-09-09 14:35:53 3 2019-10-09 14:35:53 4 2019-11-09 14:35:53 5 2019-12-09 14:35:53 6 2020-01-09 14:35:53 7 null 8 --------------------------------------- 9 min=2019-09-09 14:35:53 10 max=2020-01-09 14:35:53 11 12 Process finished with exit code 0