Evgenij Reznik
Evgenij Reznik

Reputation: 18614

Iterating nested Structure of Maps and Lists

I have the following HashMap map, containing the ArrayList content, containing several HashMaps:

{
   key1=val1,
   key2=val2,
   // ...
   content=   [
      {
         keyAbc=val10,
         keyDef=val11,
         KeyGhi=val12,
      },
      {
         keyAbc=val13,
         keyDef=val14,
         KeyGhi=val15
      },
      {
         keyAbc=val16,
         keyDef=val17,
         KeyGhi=val18
      }
   ],
   key20=val20,
   // ...
}

Now I need to get all keys and values content.


  1. Getting into the ArrayList

When I try

for(int i=0; i<map.get("content").size(); i++){}

it says cannot find symbol, as if it doesn't recognize the ArrayList.

However, casting it as an ArrayList works:

for(int i=0; i<((ArrayList)map.get("content")).size(); i++){}

  1. Getting into the HashMap

So within that loop I try:

// for(...){
   for(Map.Entry<Object, Object> obj : (((ArrayList)map.get("content")).get(i)){}
}

The following error appears:

for-each not applicable to expression type
required: array or java.lang.Iterable
found: Object

Casting as a HashMap:

// for(...){
   for(Map.Entry<Object, Object> obj : ((HashMap)(ArrayList)map.get("content")).get(i)){}
}

Produces that error:

incompatible types: ArrayList cannot be converted to HashMap


So how can I access the contents of content?

Upvotes: 1

Views: 92

Answers (3)

Rishi Saraf
Rishi Saraf

Reputation: 1812

You have to iterate through list which is value content key. I suppose below code is what you are looking for.

         for (Map<Object, Object> listEntry : (List<Map<Object, Object>>) map.get("content")) {
        for (Map.Entry innerMapEtry : listEntry.entrySet()) {
            final Object key = innerMapEtry.getKey();
            final Object value = innerMapEtry.getValue();
        }
    }

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

I will use more code to have a more human readable version of it and I replace concrete classes with interfaces (you can't be sure that the deserializer will create an ArrayList instead of another kind of List, same for Map) having the following code:

List content = (List) map.get("content");
for (Object item : content) {
  Map itemMap = (Map) item;
  for (Map.Entry entry : itemMap.entrySet()) {
     // Doing what you like with entry  
  }  
}

Upvotes: 1

Eran
Eran

Reputation: 394146

You want to iterate over the entries of the Map, so you should call entrySet:

for (Map.Entry<Object, Object> obj : ((HashMap)((ArrayList)map.get("content")).get(i)).entrySet() {}

To make it more readable, I'd break it into multiple statements. I'd also use the interface types instead of ArrayList and HashMap.

List list = (List) map.get("content");
for (int i = 0; i < list.size(); i++) {
    Map map = (Map) list.get(i);
    for (Map.Entry<Object,Object> entry : map.entrySet()) {

    }
}

Upvotes: 2

Related Questions