且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java对象的Arraylist按日期从arraylist中删除元素

更新时间:2023-01-07 08:00:39

Java 1.7 和 java.time through ThreeTen Backport

 ArrayListlist = new ArrayList();list.add( new Course(350, "5/20/2020"));list.add( new Course(350, "4/20/2019"));list.add( new Course(350, "3/20/2018"));list.add( new Course(360, "6/20/2020"));list.add( new Course(360, "5/20/2019"));list.add( new Course(370, "5/20/2020"));list.add( new Course(370, "5/19/2018"));list.add( new Course(360, "4/10/2016"));//查找每个课程编号的最新日期映射latestDates = new HashMap();对于(课程当前课程:列表){LocalDate latestHitherto = latestDates.get(currentCourse.getCourseNumber());if (latestHitherto == null || currentCourse.getDate().isAfter(latestHitherto)) {latestDates.put(currentCourse.getCourseNumber(), currentCourse.getDate());}}//删除没有最新日期的课程迭代器courseIterator = list.iterator();而 (courseIterator.hasNext()) {课程 currentCourse = courseIterator.next();如果 (currentCourse.getDate().isBefore(latestDates.get(currentCourse.getCourseNumber()))) {courseIterator.remove();}}//打印结果对于(课程当前课程:列表){System.out.format(%3d %s%n",currentCourse.getCourseNumber(),currentCourse.getDate().format(Course.dateFormatter));}

这个片段的输出是:

350 5/20/2020360 6/20/2020370 5/20/2020

我在 jdk1.7.0_67 上运行.我添加了 ThreeTen Backport 1.3.6.请参阅下面的链接.

这是我使用的 Course 类:

公开课课程{public static final DateTimeFormatter dateFormatter= DateTimeFormatter.ofPattern(M/d/u");private int courseNumber;私人本地日期;公共课程(int courseNumber,字符串日期字符串){this.courseNumber = courseNumber;this.date = LocalDate.parse(dateString, dateFormatter);}公共 int getCourseNumber() {返回课程编号;}公共本地日期 getDate() {归期;}}

如果您坚持使用 java.util.Date — 一个设计糟糕且过时的类 — (1) 我不明白您为什么要这样做,(2) 您可以将我的代码修改为改用 Date.

流版本

您可能需要考虑升级您的 Java 版本.Java 15 已经发布,并且是 Java 16 的早期访问版本. Java 8 中已经出现了流.它们将允许您以更少的代码行获得相同的结果:

 合集过滤课程 = list.stream().collect(Collectors.groupingBy(Course::getCourseNumber,Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Course::getDate)),可选::或ElseThrow))).values();列表<课程>过滤列表=新的数组列表(过滤课程);FilterList.forEach(c -> System.out.format(%3d %s%n", c.getCourseNumber(), c.getDate().format(Course.dateFormatter)));

370 5/20/2020360 6/20/2020350 5/20/2020

就代码而言,它不会在结果列表中给出相同的课程顺序,并且它需要 Java 10(在那里引入了过度的无参数 orElseThrow 方法).即使您需要相同的顺序,流仍然会非常有用.

问题:这可以在 Java 1.7 上运行吗?

java.time 在较旧和较新的 Android 设备上都能很好地工作.它只需要至少 Java 6.

  • 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 开始)中,内置了现代 API.
  • 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的向后移植(ThreeTen for JSR 310;请参阅底部的链接).
  • 在较旧的 Android 上,使用脱糖或 ThreeTen Backport 的 Android 版本.它被称为 ThreeTenABP.在后一种情况下,请确保使用子包从 org.threeten.bp 导入日期和时间类.

链接

This is my arraylist

ArrayList<Courses> list = new ArrayList<Courses>();
list.add( new Courses(350,5/20/2020) );
list.add( new Courses(350,4/20/2019 );
list.add( new Courses(350,3/20/2018) );
list.add( new Courses(360,6/20/2020) );
list.add( new Courses(360,5/20/2019) );
list.add( new Courses(370,5/20/2020) );
list.add( new Courses(370,5/19/2018) );
list.add( new Courses(360,4/10/2016) );

public class Courses{
 int coursenum;
 Date date;

}

How can I remove elements so that the arraylist contains only those elements with the latest date?

Should like this;

350, 5/20/2020}
360,6/20/2020}
370, 5/20/2020

Java 1.7 and java.time through ThreeTen Backport

    ArrayList<Course> list = new ArrayList<>();
    list.add( new Course(350, "5/20/2020") );
    list.add( new Course(350, "4/20/2019") );
    list.add( new Course(350, "3/20/2018") );
    list.add( new Course(360, "6/20/2020") );
    list.add( new Course(360, "5/20/2019") );
    list.add( new Course(370, "5/20/2020") );
    list.add( new Course(370, "5/19/2018") );
    list.add( new Course(360, "4/10/2016") );
    
    // Find latest date for each course number
    Map<Integer, LocalDate> latestDates = new HashMap<>();
    for (Course currentCourse : list) {
        LocalDate latestHitherto = latestDates.get(currentCourse.getCourseNumber());
        if (latestHitherto == null || currentCourse.getDate().isAfter(latestHitherto)) {
            latestDates.put(currentCourse.getCourseNumber(), currentCourse.getDate());
        }
    }
    
    // Remove courses that haven’t got the latest date
    Iterator<Course> courseIterator = list.iterator();
    while (courseIterator.hasNext()) {
        Course currentCourse = courseIterator.next();
        if (currentCourse.getDate().isBefore(latestDates.get(currentCourse.getCourseNumber()))) {
            courseIterator.remove();
        }
    }
    
    // Print result
    for (Course currentCourse : list) {
        System.out.format("%3d %s%n", 
                currentCourse.getCourseNumber(), 
                currentCourse.getDate().format(Course.dateFormatter));
    }

Output from this snippet was:

350 5/20/2020
360 6/20/2020
370 5/20/2020

I ran on jdk1.7.0_67. I had added ThreeTen Backport 1.3.6. See the link below.

Here is the Course class I used:

public class Course {
    
    public static final DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("M/d/u");
    
    private int courseNumber;
    private LocalDate date;
    
    public Course(int courseNumber, String dateString) {
        this.courseNumber = courseNumber;
        this.date = LocalDate.parse(dateString, dateFormatter);
    }

    public int getCourseNumber() {
        return courseNumber;
    }

    public LocalDate getDate() {
        return date;
    }
}

If you insist on using java.util.Date — a poorly designed and long outdated class — (1) I would not understand why you would, (2) you can probably modify my code to use Date instead.

Stream version

You may want consider upgrading your Java version. Java 15 is out, and an early access edition of Java 16. Already in Java 8 comes streams. They will allow you to obtain the same in much fewer lines of code:

    Collection<Course> filteredCourses = list.stream()
            .collect(Collectors.groupingBy(Course::getCourseNumber,
                    Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Course::getDate)),
                            Optional::orElseThrow)))
            .values();
    List<Course> filteredList = new ArrayList<>(filteredCourses);
    filteredList.forEach(c -> System.out.format(
            "%3d %s%n", c.getCourseNumber(), c.getDate().format(Course.dateFormatter)));

370 5/20/2020
360 6/20/2020
350 5/20/2020

As the code stands it doesn’t give the same order of courses in the resulting list, and it requires Java 10 (the overlaoded no-arg orElseThrow method was introduced there). Even if you require the same order, streams will still be extremely helpful.

Question: Can that work on Java 1.7?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links