java remove elements which match certain duplication rules from list
I have a list like this:
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);
I need to remove duplicates based on 2 out of 3 elements ("section",
"index") of the row (Map) being the same. This is what I'm trying to do:
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);
}
}
}
it fails with java.util.ConcurrentModificationException. There must be
another way of doing this, but I don't know how. Any ideas?
UPDATE: I've tried to use Iterator, as suggested, still the same exception:
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);
}
}
}
No comments:
Post a Comment