Iterate over List> in Java

后端 未结 4 1182
盖世英雄少女心
盖世英雄少女心 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:37

    You iterate over a list with elements of type Map. So casting to Map.Entry will give you a ClassCastException.

    Try it like this

    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());
        }
    }
    

    It would be easier for you, if you didn't use the raw types Iterator and Map.Entry. Use generics wherever possible. So the code would look like this:

    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());
        }
    }
    

提交回复
热议问题