I cannot iterate this structure (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:
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.
Thank you!
First, I don't think it is a good idea to have a HashMap
as a key
in another HashMap
. 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
. 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. So if h
is a HashMap<Integer, Integer>
, you loop as:
for(Map.Entry<Integer, Integer> entry : h.entrySet)
{
...
}
So, for a HashMap<HashMap<Integer, Integer>, HashMap<Integer, Integer>>
called 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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.