如何使用joda time确定数组列表中是否存在日期

How to determine if date exists in an array list using joda time

您好,我正在寻找一种更好的方法来使用 JodaTime 确定 Java 中日期列表中的日期是否存在。目前这是我正在使用的:

private static void dateSearch() {
    ArrayList<Date> dates = new ArrayList<>(); 
    dates.add(formatDate("2016-08-18T05:18:24"));
    dates.add(formatDate("2016-08-17T05:18:24"));
    dates.add(formatDate("2016-08-19T17:00:24"));
    Collections.sort(dates);
    Date today=new Date();
    int index=Collections.binarySearch(dates,today,new DateComparator());
    if(index>=0){
        System.out.println("Todays date was found " + index);
    }
}

//Here is the formatDate Function that produces date objects from strings
private static Date formatDate(String dateString) {    
    String format="yyyy-MM-dd";
    LocalDateTime dateTime = LocalDateTime.parse(dateString);
    String dateCreated = dateTime.toString(format);
    Date date = dateTime.toDate();
    return date;
}

//Here is the comparator I am using for the binary search 
private static class DateComparator implements Comparator<Date> {
    private String format="yyyy-MM-dd";

    @Override
    public int compare(Date d1,Date d2){    
        LocalDateTime dt1 = new LocalDateTime(d1);
        LocalDateTime dt2 = new LocalDateTime(d2);    
        return dt1.toString(this.format).compareTo(dt2.toString(this.format));
    }
}

我正在使用的是有效的,但恐怕在比较大量日期列表时它可能会占用大量资源和时间。 JodaTime 是否有内置的方法来做到这一点? 谢谢。

您的代码可以简化为:

List<LocalDate> dates = new ArrayList<>();
dates.add(LocalDateTime.parse("2016-08-18T05:18:24").toLocalDate());
dates.add(LocalDateTime.parse("2016-08-17T05:18:24").toLocalDate());
dates.add(LocalDateTime.parse("2016-08-19T17:00:24").toLocalDate());

System.out.println(dates.stream().anyMatch(LocalDate.now()::equals));

实际上使用 JodaTime LocalDate 而不是 java.util.Date

它不打印索引,但是,如您所说,您只想检查是否存在。

对列表进行排序具有时间复杂度 O(n log n)。如果您只想知道日期是否存在,则将在 DateComparator 中完成的转换应用于列表中的每个日期以及您要在列表中查找的日期。那么只要用List.contains判断是否包含该元素即可。这具有复杂性 O(n).