What would be the correct method for being able to search a key of a TreeMap<Date, String> such as NavigableMap<Date, String>? In which I wish to check by a specific month and output all those with that month?
For example if it looks like below, how would I be able to search for all those with the key February?
Date date1 = dateformat.parse("8 January 2013");
If using a NavigableMap implementation, you can call subMap to get a view of the map between two keys:
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
//using TreeMap for example
NavigableMap<Date, String> stringsByDate = new TreeMap<Date, String>();
//populate map
Date jan15th = dateFormat.parse("15 January 2013");
Date feb12th = dateFormat.parse("12 February 2013");
Date feb24th = dateFormat.parse("24 February 2013");
Date march18th = dateFormat.parse("18 March 2013");
stringsByDate.put(jan15th, "foo");
stringsByDate.put(feb12th, "bar");
stringsByDate.put(feb24th, "baz");
stringsByDate.put(march18th, "qux");
//define "from" and "to" keys
Date feb1st = dateFormat.parse("1 February 2013");
Date march1st = dateFormat.parse("1 March 2013");
//get the specified view
NavigableMap<Date, String> febStringsByDate = stringsByDate.subMap(
feb1st,
true, //include Feb 1st
march1st,
false //don't include March 1st
);
//prints {Tue Feb 12 00:00:00 EST 2013=bar, Sun Feb 24 00:00:00 EST 2013=baz}
System.out.println(febStringsByDate);
As demonstrated the "from" and "to" keys used in the call to subMap do not themselves need to be contained in the map.
NOTE: This will only work for the dates of a specific February, e.g. February 2013. If you need entries for all February dates, you will need to iterate by year and consolidate the results.
First of all, Date is mutable and using mutable objects as a key in Map, is not recommended.
but to answer your question: you need to iterate over keys in your map and check each one against the given criteria. you can wrap Date into Calendar class to make day, month, year and ... comparison easier.
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