【问题标题】:Update entry while iterating through key set遍历键集时更新条目
【发布时间】:2012-07-07 10:24:16
【问题描述】:

如何在遍历键时完成更新条目

Map<String,List<SObject>> Map1=new HashMap<String,List<SObject>>();
Map<String,List<SObject>> Map2=new HashMap<String,List<SObject>>();

for(String name: Map1.keyset()){
//do something

   for(SObject obj1: Map1.get(name)){
    //iterate through the list of SObjects returned for the key 

        for(SObject obj2 : Map2.get(name)){
        //iterate through the list of SObject values for the keys and update or remove the values related to the key
        }
   }
 }

【问题讨论】:

    标签: java map iterator


    【解决方案1】:

    您可以在地图的 entrySet 上使用 Iterator - map.entrySet().iterator()

    确保在您迭代地图时没有其他任何东西在修改地图,但您自己的修改将是安全的,只要您:

    - only remove items using the iterator's remove() method, and
    - only modify a value by using the Map.Entry setValue() method
    

    http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#entrySet()

    【讨论】:

      【解决方案2】:

      要在迭代期间修改集合,您需要使用ListIteration 接口:

      http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 2014-05-04
        • 2022-06-28
        • 2014-09-15
        相关资源
        最近更新 更多