在Java中迭代List <Map >
我正在尝试在Java中迭代List<Map>
。 但是,我无法正确迭代它。 任何人都可以指导我吗?
Iterator it = list.iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); }
谢谢,
public static void main(String[] args) { List
产量
Data For Map0 Key = Fname , Value = Ankur Data For Map1 Key = Lname , Value = Singhal
忘记直接使用迭代器,为什么不简单:
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 } }
这称为增强型循环 。 在内部,它将处理它作为遍历任何集合的迭代器或Iterable
接口的任何其他实现的for循环。
它已经用于在一个答案中遍历地图条目,那么为什么不用于地图列表呢?
当然,对于嵌套集合,您还需要知道如何嵌套for循环(如何将一个for循环放在另一个循环中)。
您使用Map
类型的元素迭代列表。 因此,转换为Map.Entry
将为您提供ClassCastException
。
试试吧
Iterator it = list.iterator(); while (it.hasNext()) { Map map = (Map) it.next(); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } }
如果您没有使用原始类型Iterator
和Map.Entry
,那么对您来说会更容易。 尽可能使用generics。 所以代码看起来像这样:
Iterator> it = list.iterator(); while (it.hasNext()) { Map map = it.next(); //so here you don't need a potentially unsafe cast for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } }
list没有entySet()方法!
尝试这个:
final Iterator> it = list.iterator(); while (it.hasNext()) { Map mapElement = it.next(); // do what you want with the mapElement }
当然,您需要另一个循环来迭代地图中的元素。