[英]java: check if an object's attribute exists in HashMap values
我有一个HashMap,其键类型为Double
,我的自定义对象为value 。 看起来像这样:
private static Map<Double, Incident> incidentHash = new HashMap<>();
Incident
对象具有以下属性: String date
, String address
, String incidentType
。
现在,我有一个从用户那里得到的String date
作为输入,我想检查在HashMap中是否存在任何使用该用户输入日期的事件。 给定日期的HashMap中可以有很多事件,但是只要给定日期至少有一个事件,我就可以做某事 。
我可以遍历HashMap中的所有值并检查是否存在给定的日期,但是我想知道是否存在不修改数据结构的更好,更有效的方法。
您可以使用流API(来自Java8),如以下代码所示,并带有内联注释:
String userInput="10-APR-2017";
Optional<Map.Entry<Double, Incident>> matchedEntry =
incidentHash.entrySet().stream().
//filter with the condition to match
filter(element -> element.getValue().getDate().equals(userInput)).findAny();
//if the entry is found, do your logic
matchedEntry.ifPresent(value -> {
//do something here
});
如果您正在寻找JDK1.8之前的版本,则可以参考以下代码:
String userInput="10-APR-2017";
Set<Map.Entry<Double, Incident>> entries = incidentHash.entrySet();
Map.Entry<Double, Incident> matchedEntry = null;
for(Iterator<Map.Entry<Double, Incident>> iterator = entries.iterator();
iterator.hasNext();) {
Map.Entry<Double, Incident> temp = iterator.next();
if(temp.getValue().getDate().equals(userInput)) {
matchedEntry = temp;
break;
}
}
给定您的HashMap, 否 ,没有其他方法可以对HashMap进行迭代 。
至于更改结构,您可以将Map<String, List<Incident>>
用作方法,这样就可以将date
作为键,并根据需要设置该日期的事件List
: There can be many Incidents in the HashMap with the given date
。
所以这将是O(1)
//considering that the key is added when you have at least one incident
if (yourHash.get("yourDateStringWhatEverTheFormatIs") != null)
您可以将TreeMap与自定义Comparator一起使用 。 在比较器中比较日期的值。
您将不得不遍历地图,直到找到匹配的数据。 由于您只需要知道是否存在任何事件,您可以在找到匹配项时直接退出循环,而无需遍历地图的其余部分。
您只能保留第二个将属性与对象匹配的Hash / TreeMap,因此您也可以快速检查此属性。 但是,您必须为要快速访问的每个属性创建一个这样的映射。 这使它更加复杂并使用更多的内存,但速度可能要快得多。
如果这不是一个选择,则在其他答案中引用的流API是一种迭代所有对象以搜索属性的好方法。
private static Map<Double, Incident> incidentHash = new HashMap<>();
private static Map<String, List<Incident>> incidentsPerDayMap = new HashMap<>();
鉴于您不想iterate
Map,并且当前它是获取所需值的唯一方法,因此我建议您重新推荐另一个包含Date
作为键和List<Incident>
作为值的Map
。 它可以是TreeMap
,例如:
Map<Date, List<Incident>> incidents = new TreeMap<>();
你可以put
这个入口Map
,每当项被添加到原来的Map
,例如:
Incident incident = ;// incident object
Date date; //Date
incidents.computeIfAbsent(date, t -> new ArrayList<>()).add(incident);
用户输入Date
,您可以仅通过incidents.get()
获取属于该日期的所有事件。 尽管这将为您提供一个list
并且您仍然需要对其进行迭代,但是它将包含更少的元素,并且TreeMap
get
方法将确保您在排序时log n
复杂性。 因此,您的搜索操作将更加高效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.