繁体   English   中英

如何从ArrayList中删除null {}映射 <HashMap<String, String> &gt;?

[英]How to remove null { } map from ArrayList<HashMap<String, String>>?

我有一个ArrayList<HashMap<String, String>> placesListItems

当我从placesListItems删除地图时,将保留空地图。 这样我的ListAdapter包含空列表项。

for (HashMap<String, String> map : placesListItems) {
  for (Entry<String, String> entry : map.entrySet()) {
    for (int j = 0; j < duplicateList.size(); j++) {
      if (entry.getValue().equals(duplicateList.get(j))) {
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
          Entry<String, String> pairs = (Entry)iterator.next();
          System.out.println(pairs.getKey() + " = " + pairs.getValue());
          iterator.remove(); // avoids a ConcurrentModificationException
        }
      }
    }
  }
}     
ListAdapter adapter = new ItemAdapterHome(getApplicationContext, placesListItems);
lv.setAdapter(adapter); 

我该如何解决?

您需要做的是在列表中添加所有空地图,并在最后将其全部删除。

List<HashMap<String, String>> mapsToRemove= new ArrayList<HashMap<String, String>>();//list in which maps to be removed will be added
for (HashMap<String, String> map : placesListItems)
   {
    for (Entry<String, String> entry : map.entrySet())
     {
      for (int j = 0; j < duplicateList.size(); j++) 
          {
        if(entry.getValue().equals(duplicateList.get(j)))
         {
          Iterator iterator = map.entrySet().iterator();
          while (iterator.hasNext()) 
               {
              Entry<String, String> pairs = (Entry)iterator.next();
              System.out.println(pairs.getKey() + " = " + pairs.getValue());
              iterator.remove(); // avoids a ConcurrentModificationException                   }
               }
          }
      }
      if(map.isEmpty){//after all above processing, check if map is empty
         mapsToRemove.add(map);//add map to be removed
      }
 }  
placesListItems.removeAll(mapsToRemove);//remove all empty maps


ListAdapter adapter = new ItemAdapterHome(getApplicationContext, placesListItems);
lv.setAdapter(adapter); 

您可能需要根据需要稍微更改逻辑。

您的问题是您要清空地图,而不是将其从列表中删除。

请尝试以下操作:

Iterator<Map<String, String>> iterator = placesListItems.iterator();
while (iterator.hasNext()) {
    Map<String, String> map = iterator.next();
    for (String value : map.values()) {
        if (duplicateList.contains(value)) { // You can iterate over duplicateList, but List.contains() is a nice shorthand.
            iterator.remove(); // Removing the map from placesListItems
            break; // There is no point iterating over other values of map
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM