JAVA8新特性lambda表达式(时间为空排序)

对象时间排序,如果时间为空放到最后


public class DataVo {

    /**
     * ID
     */
    private String id;

    /**
     * 时间
     */
    private Date date;
}

 public static void main(String[] args) {

        List dataVos = new ArrayList<>();
        DataVo dataVo1 = new DataVo();
        dataVo1.setDate(new Date());
        dataVo1.setId("1");
        dataVos.add(dataVo1);

        DataVo dataVo2 = new DataVo();
        dataVo2.setId("2");
        dataVos.add(dataVo2);

        DataVo dataVo3 = new DataVo();
        dataVo3.setId("3");
        dataVo3.setDate(new Date());
        dataVos.add(dataVo3);

        dataVos = dataVos.stream().sorted(Comparator.comparing(d -> d.getDate(), Comparator.nullsLast(Date::compareTo))).collect(Collectors.toList());

        dataVos.forEach(data -> System.out.println(data));
    }
  • 结果
DataVo{id='1', date=Tue Aug 20 10:07:49 CST 2019}
DataVo{id='3', date=Tue Aug 20 10:07:49 CST 2019}
DataVo{id='2', date=null}

你可能感兴趣的:(JAVA8新特性lambda表达式(时间为空排序))