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).
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With