Browse Hashmap<Integer, Hashmap<Integer, Arraylist<Integer>>

Asked

Viewed 1,595 times

1

I got the following HashMap:

HashMap<Integer,HashMap<Integer,ArrayList<Integer>>> hm = new HashMap<>();

When I do this:

Set<Integer> keys = hm.keySet();
for(int i : keys) System.out.println(i + ": " +hm.get(i));

I have an output like:

2: {2=[1, 2, 3, 4]}

How can I walk the HashMap to have access to the keys and values of the HashMap inland?

1 answer

7


You must do it separately, this is go through the main and for each iteration go through the secondary.

code:

for(Map.Entry<Integer,HashMap<Integer,ArrayList<Integer>>> kv: hm.entrySet()){
      //percorre map principal
      System.out.println("Key: "+kv.getKey()); //chave do principal
      //busca o map inferior dessa key 
      HashMap<Integer,ArrayList<Integer>> secondmap= kv.getValue();
      //percorre o map inferior
      for(Map.Entry<Integer,ArrayList<Integer>> kvv: secondmap.entrySet() ){
           //faz o print da chave e de todos os valores do arraylist
           for (int valor : kvv.getValue()){                               
                  System.out.println("Key: "+kvv.getKey() + "value "+valor;
           }

      }

}
  • Thanks for the help. gives me an error in the first line of your code: "Wrong number of type Arguments: required: 2"

  • This code has not been tested by any ide, so you should have some attention to the code, error in etry - stays entry

  • 1

    Yeah, I figured that out, and I fixed it. I think that in the first line of your code the 'Hashmap' has to leave and is: 'for(Map.Entry<Integer,Hashmap<Integer,Arraylist<Integer>>> Kv: hm.entryset()){'

  • 2

    @Hugomachado sees now

  • That’s how it worked ! Thanks for the help :D Just one more question later, I can go through the last Arraylist at the end?

  • 1

    for (int valor : kvv.getValue()){&#xA; System.out.println("arrayListvalores: "+ valor);&#xA;}

  • Yes it follows the same logic creates the list, assigns to that list the value of kvv.getvalue and then just go through

  • I’ll edit the question and if you can see if I’m doing something wrong I’d appreciate it.

  • @Hugomachado put the code there

  • I was distracted didn’t see it. Thanks @Jorgeb. it worked ;)

  • 1

    @Hugomachado reversed your question because the "correction" you put is the answer you find here.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.