Every Java Map iteration example I’ve seen recommends this paradigm:
for (Map.Entry<String, String> item : hashMap.entrySet()) { String key = item.getKey(); String value = item.getValue(); }
However, when I attempt to do this I get a warning from my compiler:
Incompatible types: java.lang.Object cannot be converted to java.util.Map.Entry<java.lang.String, java.lang.Object>
Here’s my code – the only wrinkle I see is that I’m iterating over an array of Map objects, and then iterating over the elements of the individual Map:
result = getArrayOfMaps(); // Force to List LinkedHashMap List<LinkedHashMap> result2 = new ArrayList<LinkedHashMap>(); for (Map m : result) { LinkedHashMap<String, Object> n = new LinkedHashMap<>(); for (Map.Entry<String, Object> entry : m.entrySet()) { n.put(entry.getKey(),entry.getValue()); } result2.add(n); }
Am I missing something blatantly obvious?
Advertisement
Answer
This is happening because you are using raw types: a List<LinkedHashMap>
instead of a List<LinkedHashMap<Something, SomethingElse>>
. As a result, the entrySet
is just a Set
instead of a Set<Map.Entry<Something, SomethingElse>>
. Don’t do that.