Java hashmap search keys for a date

12,329

This code will do the trick:

public static void findEvents(Map<Date, Event> dateEvents, Date targetDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    String target = dateFormat.format(targetDate); 
    for (Map.Entry<Date, Event> entry : dateEvents.entrySet()) {
        if (dateFormat.format(entry.getKey()).equals(target)) {
            System.out.println("Event " + entry.getValue() + " is on the specified date");
        }
    }
}

The important thing here is that all dates are converted to a String with format "dd.MM.yyyy" before comparing, so any differences in hour/minute/second still match if the day is the same.

This code also demonstrates the best way (IMHO) to iterate over a map.

Share:
12,329
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a hashmap: Map dateEvent = new HashMap(); where key is a date and time and value is a string. I fill collection with data where date is in format dd.MM.yyyy HH:mm. How I can get all keys with date based on this format: dd.MM.yyyy?

  • musiKk
    musiKk over 12 years
    If you need both key and value this sure is the best way to iterate over a map. Code analyzers such as FindBugs will note this too.
  • Dejell
    Dejell over 9 years
    "(If you do this, it is not recommended that you base that class on another class that already defines these methods (e.g. java.util.Date).)" why?
  • musiKk
    musiKk over 9 years
    @Dejel Pretty sure this goes against the contract. java.util.Date#equals() states the two dates have to be equal to the millisecond in order to be equal.