无法使用java迭代map <string,string =“”>的列表

时间:2015-06-26 05:37:10

标签: java

我试图迭代一个内部有地图的列表对象..这是我的代码

public Response updateStatus(List<Map<String, String>> leadIds) {
    Iterator it = leadIds.iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry) it.next();
        LOG.info("Key: "+pairs.getKey() + " Value: " + pairs.getValue());
    }

潜在客户ID具有以下值

[{Id=1066276530, Key1=1815401000238}, {Id=1059632250, Key1=1815401000244}]

但是,我收到以下错误

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.Map$Entry

3 个答案:

答案 0 :(得分:0)

您需要两个循环来迭代List中包含的地图:

public Response updateStatus(List<Map<String, String>> leadIds) {
    Iterator<Map<String, String>> listIt = leadIds.iterator();
    while (listIt.hasNext()) {
      Iterator<Map.Entry<String, String>> it = listIt.next().entrySet().iterator();
      while (it.hasNext()) {
          Map.Entry<String,String> pairs = it.next();
          LOG.info("Key: "+pairs.getKey() + " Value: " + pairs.getValue());
      }
    }
}

BTW,Java 8为这种迭代提供了一个更短的API:

leadIds.stream()
       .flatMap(m->m.entrySet().stream())
       .forEach(entry -> {
                          LOG.info("Key: "+entry.getKey() + " Value: " + entry.getValue());
                         });

答案 1 :(得分:0)

这是一种简单的方法:

public Response updateStatus(List<Map<String, String>> leadIds) {
    for (Map<String, String> map : leadIds) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            LOG.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }
    }
}

此代码已经过测试,似乎运行正常。需要注意的是:对map.entrySet()的调用会返回包含条目的Set,而且似乎是无序的。所以我的代码肯定记录所有键/值对,但不一定按特定顺序记录。

答案 2 :(得分:0)

你需要第二个循环。 改为:

public Response updateStatus(List<Map<String, String>> leadIds) {
    Iterator<Map<String, String>> it = leadIds.iterator();
    while (it.hasNext()) {
        Map<String, String> m = it.next();
        Iterator it1 = m.entrySet().iterator();
        while (it1.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it1
                    .next();
              LOG.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }
    }