Java hashmap search keys for date

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

+4
source share
4 answers

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"); } } } 

It is important to note that all dates are converted to String with the format "dd.MM.yyyy" before comparison, so any differences in hours / minutes / seconds still match if the day is the same.

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

+10
source

Not sure if I'm right. However, you get a set of keys from the map using map.keySet() . If you want to find all the different dates, fill in all the dates in the set. If you want to reduce the accuracy to a few days, one solution would be to convert the date to the desired format and add these lines to the set. Duplicates will be deleted automatically.

For instance:

 Map<Date, String> yourMap = [..]; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy"); Set<String> differentDates = new HashSet<String>(); for (Date date: yourMap.keySet()) { differentDates.add(simpleDateFormat.format(date)); } 
0
source

You have (at least) two options:

You can write your own Date class that provides the corresponding hashCode() and equals() implementations. (If you do, it is not recommended that you base this class on another class that already defines these methods (e.g. java.util.Date ).)

An alternative to brute force is to check all keys regardless of whether they match your criteria.

0
source

There is no difference between the date 01.01.2011 (dd.MM.yyyy) and the date 01.01.2011 00:00 (dd.MM.yyyy HH: mm).

Date contains a long that has hours and minutes. Even for public Date(int year, int month, int date)

0
source

All Articles