使用Date作为密钥Java的Treemap

Mel*_*lky 2 java date treemap

能够搜索TreeMap<Date, String>诸如此类的密钥的正确方法是NavigableMap<Date, String>什么?我希望在特定月份检查并输出那个月的所有人?

例如,如果它如下所示,我将如何能够搜索所有关键二月份的人?

Date date1 = dateformat.parse("8 January 2013");
Run Code Online (Sandbox Code Playgroud)

Pau*_*ora 7

如果使用NavigableMap实现,您可以调用subMap以获取两个键之间的映射视图:

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);
Run Code Online (Sandbox Code Playgroud)

如所示,调用中使用的"from"和"to"键subMap本身不需要包含在地图中.

注意:这仅适用于特定 2月的日期,例如2013年2月.如果您需要所有 2月份日期的条目,则需要按年份进行迭代并合并结果.