如何根据日期从ArrayList中获取最新记录

问题描述 投票:2回答:3

我有以下记录列表。我想根据日期获取最新记录,并将其名称设置为“ H”。以同样的方式,我想为所有剩余记录设置“ L”作为名称。

List<Student> studentList = new ArrayList<>();

try {
  studentList.add(new Student("A", new SimpleDateFormat("dd-MM-yyyy").parse("01-01-1990")));
  studentList.add(new Student("B", new SimpleDateFormat("dd-MM-yyyy").parse("01-01-2010")));
  studentList.add(new Student("C", new SimpleDateFormat("dd-MM-yyyy").parse("01-01-2011")));
  studentList.add(new Student("D", new SimpleDateFormat("dd-MM-yyyy").parse("01-01-2012")));
  studentList.add(new Student("E", new SimpleDateFormat("dd-MM-yyyy").parse("01-01-2018")));

} catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();  
}

Student student = Collections.max(studentList, Comparator.comparing(s -> s.getDate()));

我已经如上所述尝试过,但是在这里我只能为最新记录设置名称,但无法为所有其他剩余记录设置名称。

任何帮助将不胜感激。

java java-8
3个回答
3
投票

单线程版本:


1
投票

如果只有日期,请使用Java-8中的LocalDateDateTimeFormatter


0
投票

只需遍历您的列表并根据需要设置名称:

© www.soinside.com 2019 - 2024. All rights reserved.