Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java: can't use Map.Entry to iterate over a Map?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading