[英]Cannot iterate 2 hashmaps in a hashmap
I cannot iterate this structure (Java): 我无法迭代此结构(Java):
HashMap<HashMap<Integer, Integer>, HashMap<Integer, Integer>> last
= new HashMap<HashMap<Integer, Integer>, HashMap<Integer, Integer>>();
These are the 2 HashMaps that I am adding into the first: 这些是我要添加到第一个的2个HashMap:
HashMap<Integer, Integer> arrival = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> departure = new HashMap<Integer, Integer>();
Tried various loops, read a couple of articles but I cannot connect the dots to make it correct until now. 尝试了各种循环,阅读了几篇文章,但直到现在为止我都无法将其正确理解。
I want for example to be able to get/print the four integer values from the two HashMaps in the HashMap together in the loop. 我希望例如能够在循环中从HashMap中的两个HashMap中获取/打印四个整数值。
Thank you! 谢谢!
First, I don't think it is a good idea to have a HashMap
as a key
in another HashMap
. 首先,我认为将HashMap
作为另一个HashMap
的key
不是一个好主意。 It looks like you are representing a map of key value pairs (arrival/destination?), you would be better off creating an class just for that and adding that class to a HashMap
. 看起来您正在代表键值对(到达/目的地?)的映射,最好为此创建一个类并将该类添加到HashMap
。 Using your current structure will cause more confusion than benefits. 使用您当前的结构会带来更多的混乱,而不是收益。
That said, it is possible to loop through this. 这就是说,有可能通过这个循环。
One way to loop through a HashMap is to loop trhough its entry set. 遍历HashMap的一种方法是遍历其条目集。 So if h
is a HashMap<Integer, Integer>
, you loop as: 因此,如果h
是HashMap<Integer, Integer>
,则循环为:
for(Map.Entry<Integer, Integer> entry : h.entrySet)
{
...
}
So, for a HashMap<HashMap<Integer, Integer>, HashMap<Integer, Integer>>
called last
因此,对于HashMap<HashMap<Integer, Integer>, HashMap<Integer, Integer>>
被称为last
for(Map.Entry<HashMap<Integer, Integer>, HashMap<Integer, Integer>> entry : last.entrySet())
{
HashMap<Integer, Integer> key = entry.getKey();
for(Map.Entry<Integer, Integer> keyMapEntry : key.entrySet())
{
//Loop through the value HashMap.
//keyMapEntry.getKey() gives the key of the Hashmap that is the key in the
//original Hashmap, keyMapEntry.getValue() gives the value
}
HashMap<Integer, Integer> value = entry.getValue();
for(Map.Entry<Integer, Integer> valueMapEntry : value.entrySet())
{
//Loop through the key HashMap
//valueMapEntry.getKey() gives the key of the Hashmap that is the value in the
//original Hashmap, valueMapEntry.getValue() gives the value
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.