0

I would like to output all the key/value pairs from a List < Map < String, String>>. How can I accomplish this?

I have already tried the following:

public void myFunction (List<Map<String,String>> list){
    Iterator <Map<String, String>> iterator = list.iterator();
    while (iterator.hasNext()){
        for (String key: ((Map<String, String>) iterator).keySet()){
            System.out.println(key + " " + ((Map<String, String>) iterator).get(key).toString());
        }
    }
}

But I get a java.lang.ClassCastException: java.util.ArrayList$Itr cannot be cast to java.util.Map exception.

What am I doing wrong? Or what can I do alternatively?

MKhowaja
  • 62
  • 1
  • 10

4 Answers4

1
    List<Map<String,String>> list = null;

    for(Map<String,String> m : list){
        for(Entry<String, String> en : m.entrySet()){
            System.out.println(en.getKey());
            System.out.println(en.getValue());
        }
    }

For each map in the list, loop over each entry in it's entry set. This way you don't have to worry about an iterator, as it is a simple foreach loop.

Mike Elofson
  • 2,017
  • 1
  • 10
  • 16
0

You hadn't called next() on the iterator and retrieved the map. Do this once at the top of your while loop and refer to map therefter:

Iterator <Map<String, String>> iterator = list.iterator();
while (iterator.hasNext()){
    Map<String, String> map = iterator.next();

    for (String key: map.keySet()){
        System.out.println(key + " " + map.get(key).toString());
    }
}

Note: consider using code from one of the other answers - for each loops are much neater.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
0

Map#keySet() returns a Set not a Map, hence the ClassCastException.

You could proceed as follow:

for(Map<String, String> map : list) {
    for(Entry<String, String> e: map.entrySet()) {
        System.out.println("Key=" + e.getKey() + ", Value=" + e.getValue());
    }
}

Note tha if you want to iterate over all entries of a map it is better to use Map#entrySet instead of keySet() and calling Map#get each time. You dont always know how hashcode and equals of a class is implemented.

A4L
  • 17,353
  • 6
  • 49
  • 70
0

If I understand your question, you could use a for-each loop and the keySet() like so,

List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String,String> testMap = new HashMap<String, String>();
testMap.put("Hello", "World");
testMap.put("Goodbye", "World");

list.add(testMap);
for (Map<String, String> map : list) {
    for (String key : map.keySet()) {
        System.out.printf("%s = %s\n", key, map.get(key));
    }
}

Output is

Goodbye = World
Hello = World
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249