Iterate over List> in Java

后端 未结 4 1181
盖世英雄少女心
盖世英雄少女心 2020-12-17 08:16

I\'m trying to iterate List> in Java. However, I\'m not able to iterate it properly. Can any one guide me?

Itera         


        
4条回答
  •  甜味超标
    2020-12-17 08:41

    Forget using the iterator directly, why not simply this:

    List> l = new ArrayList<>();
    ...
    // add map elements to list
    ...
    
    for (Map m:l) {
      for (Map.Entry e:m.entrySet()) {
        String key = e.getKey();
        String value = e.getValue();
        // Do something with key/value
      }
    }
    

    This is called an Enhanced for Loop. Internally it will handle it as a for loop traversing the iterator of any collection, or any other implementation of the Iterable Interface.

    It was already used for traversing the Map Entries in one answer, so why not for the list of maps?

    Of course, for nested collections, you also need to know how to nest your for-loops (how you put one for loop inside the other).

提交回复
热议问题