我有一个这样的列表:
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> row;
row = new HashMap<String, String>();
row.put("page", "page1");
row.put("section", "section1");
row.put("index", "index1");
list.add(row);
row = new HashMap<String, String>();
row.put("page", "page2");
row.put("section", "section2");
row.put("index", "index2");
list.add(row);
row = new HashMap<String, String>();
row.put("page", "page3");
row.put("section", "section1");
row.put("index", "index1");
list.add(row);
我需要根据行(地图)的 3 个元素(“节”、“索引”)中的 2 个相同来删除重复项。这就是我想要做的:
for (Map<String, String> row : list) {
for (Map<String, String> el : list) {
if (row.get("section").equals(el.get("section")) && row.get("index").equals(el.get("index"))) {
list.remove(el);
}
}
}
它失败了java.util.ConcurrentModificationException
。必须有另一种方法可以做到这一点,但我不知道如何。有任何想法吗?
更新:按照建议,我尝试使用迭代器,但仍然是相同的异常:
Iterator<Map<String, String>> it = list.iterator();
while (it.hasNext()) {
Map<String, String> row = it.next();
for (Map<String, String> el : list) {
if (row.get("section").equals(el.get("section")) && row.get("index").equals(el.get("index"))) {
list.remove(row);
}
}
}
UPDATE2:这失败了同样的例外:
Iterator<Map<String, String>> it = list.iterator();
while (it.hasNext()) {
Map<String, String> row = it.next();
Iterator<Map<String, String>> innerIt = list.iterator();
while (innerIt.hasNext()) {
Map<String, String> el = innerIt.next();
if (row.get("section").equals(el.get("section")) && row.get("index").equals(el.get("index"))) {
innerIt.remove();
//it.remove(); //fails as well
}
}
}
更新 3,解决方案:非常简单:
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (list.get(i).get("section").equals(list.get(j).get("section")) && list.get(i).get("index").equals(list.get(j).get("index"))) {
list.remove(i);
}
}
}
更新 4: “解决方案”没有按预期工作。现在选择正确答案。