Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a list of dates contains a particular date

I am looking for a better way checking if a List of java.util.Date objects (ArrayList, which is returned to me). The scenario is, I am returned a List of dates, and I would like to find out if a date I have on hand is within the List of dates I was returned.

Currently what I am doing is looping the List and using JodaTime to compare the dates.

Note: Only the date part should be considered while comparing the dates (not the time part).

like image 505
Oh Chin Boon Avatar asked Jul 28 '12 01:07

Oh Chin Boon


2 Answers

Write your own Comparator. You could use this to perform the individual comparisons of the Date objects

public class MyDateComparator implements Comparator<Date> {
    protected static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    public int compare(Date d1, Date d2) {
        return DATE_FORMAT.format(d1).compareTo(DATE_FORMAT.format(d2));
    }
}


Date myDate = ...
List<Date> listOfDates = ...
Collections.sort(listOfDates);
int index = Collections.binarySearch(listOfDates, myDate, new MyDateComparator());
if (index >= 0) {
  // you found me
}

(typed with fat fingers on iPad, rocking 3 month old to sleep, apologies for minor mistakes)

like image 165
MadProgrammer Avatar answered Nov 14 '22 22:11

MadProgrammer


Two java.util.Date objects are equal() if they resolve to the same millisecond. So you can use List.contains():

http://docs.oracle.com/javase/6/docs/api/java/util/List.html#contains%28java.lang.Object%29 http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#equals%28java.lang.Object%29

List<Date> dates = ...
Date targetDate = ...
if (dates.contains(targetDate)) { ... }

Alternatively, if you know the list is sorted you could use Collections.binarySearch()

http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20java.lang.Object%29

like image 35
dnault Avatar answered Nov 14 '22 21:11

dnault