我有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);
我该如何解决这个问题?
答案 0 :(得分: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);
您可能需要根据您的要求稍微更改逻辑。
答案 1 :(得分: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
}
}
}