简体   繁体   English

用于日期的Java hashmap搜索键

[英]Java hashmap search keys for a date

I have a hashmap: Map dateEvent = new HashMap(); 我有一个hashmap:map dateEvent = new HashMap(); where key is a date and time and value is a string. 其中key是日期和时间,value是字符串。 I fill collection with data where date is in format dd.MM.yyyy HH:mm. 我用数据填充集合,其中日期格式为dd.MM.yyyy HH:mm。 How I can get all keys with date based on this format: dd.MM.yyyy? 如何根据这种格式获取所有日期键:dd.MM.yyyy?

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. 这里重要的是在比较之前将所有日期转换为格式为“dd.MM.yyyy”的字符串,因此如果日期相同,则小时/分钟/秒的任何差异仍然匹配。

This code also demonstrates the best way (IMHO) to iterate over a map. 此代码还演示了迭代地图的最佳方式(恕我直言)。

Not sure whether I get you right. 不确定我是否帮助你。 However, you get the set of keys from a map using map.keySet() . 但是,您可以使用map.keySet()从地图中获取一组键。 If you want to find all different dates fill all dates into a set. 如果要查找所有不同的日期,请将所有日期填入集合中。 If you want to reduce the accuracy to days, one solution would be to convert the date to the desired format and add those strings to a set. 如果要将精度降低到几天,一种解决方案是将日期转换为所需格式并将这些字符串添加到集合中。 Duplicates will be removed automatically. 重复项将自动删除。

Eg: 例如:

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

You have (at least) two options: 你有(至少)两个选择:

You could write your own Date class which supplies appropriate implementations of hashCode() and equals() . 您可以编写自己的Date类,它提供hashCode()equals()适当实现。 (If you do this, it is not recommended that you base that class on another class that already defines these methods (eg java.util.Date ).) (如果这样做,不建议您将该类基于已定义这些方法的另一个类(例如java.util.Date )。)

The brute force alternative is to scan all keys whether they fit your criteria. 蛮力替代方案是扫描所有键是否符合您的标准。

There is no difference between between the Date 01.01.2011 (dd.MM.yyyy) and the Date 01.01.2011 00:00 ( dd.MM.yyyy HH:mm) . 日期01.01.2011 (dd.MM.yyyy)和日期01.01.2011 00:00dd.MM.yyyy HH:mm)之间没有区别。

Date holds a long which has hours and minutes. Date持有一个long ,有几小时和几分钟。 Even for public Date(int year, int month, int date) 即使是public Date(int year, int month, int date)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM