1

我有一个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); 

我该如何解决这个问题?

4

2 回答 2

3

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

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

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

于 2013-05-16T08:36:24.557 回答
2

您的问题是您正在清空地图而不是从列表中删除它们。

尝试以下操作:

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
        }
    }
}
于 2013-05-16T08:45:31.440 回答