-1

I am attempting to access an ArrayList within a HashMap and iterate over it. However I am currently running into an issue with the following setup.

Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list = Arrays.asList("One", "Two", "Three");
map.put("key_one", list);

Iterator it = map.entrySet().iterator();

while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    log.info(pair.getKey());
    log.info(pair.getValue().getClass());
    for (String element : pair.getValue()) {
        log.info(element);
    }
}

There is something with accessing the ArrayList that is giving me issues.

[ERROR] required: array or java.lang.Iterable

[ERROR] found: java.lang.Object

If I access the list outside of the map, everything works fine. Its just accessing within the HashMap.

Any guidance would be most appreciated. Thank you for your time.

Warm Regards

Mike Croteau
  • 1,062
  • 2
  • 16
  • 43
  • No, really, it's because you're using raw types. If you [ask the same question with the same problem](https://stackoverflow.com/questions/52919831/how-do-you-iterate-over-inner-list-on-arrays-object-is-defining-as-arrays-aslis?noredirect=1#comment92749277_52919831), I'll close it for the same reason. – Andy Turner Oct 21 '18 at 21:53

2 Answers2

1

I would iterate over a setup like that as follows:

Map<String, List<String>> map = new HashMap<>();
List<String> list = Arrays.asList("One", "Two", "Three");

for (Map.Entry<String, List<String>> mapValue : map.entrySet()) {
    for (String listValue : mapValue.getValue()) {
        // Do stuff

    }
}

The reason your code is not working is because you're defining pair as Map.Entry pair = (Map.Entry)it.next();, without any types. This causes pair.getValue() to return Object and not some sort of List, which is why you cannot iterate over it in the for loop.

A fix using your code would be to change:

Map.Entry pair = (Map.Entry)it.next();

to:

Map.Entry<String, List<String>> pair = (Map.Entry<String, List<String>>) it.next();
Mark
  • 5,089
  • 2
  • 20
  • 31
0

You just had to use generics in your code and then it works perfect. Here is your code with generics,

Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list = Arrays.asList("One", "Two", "Three");
map.put("key_one", list);

Iterator<Entry<String, List<String>>> it = map.entrySet().iterator();

while (it.hasNext()) {
    Map.Entry<String, List<String>> pair = it.next();
    System.out.println(pair.getKey());
    System.out.println(pair.getValue().getClass());
    for (String element : pair.getValue()) {
        System.out.println(element);
    }
}
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36