Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treemap using Date as the Key Java

Tags:

java

date

treemap

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");
like image 574
Melky Avatar asked Jun 28 '26 09:06

Melky


2 Answers

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.

like image 124
Paul Bellora Avatar answered Jun 29 '26 23:06

Paul Bellora


  • 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.

like image 21
mhshams Avatar answered Jun 29 '26 22:06

mhshams