I have quite large List named items (>= 1,000,000 items) and some condition denoted by
I would imagine that building a new list, rather than modifying the existing list, would be more performant - especially when the number of items is as large as you indicate. This assumes, your list is an ArrayList
, not a LinkedList
. For a non-circular LinkedList
, insertion is O(n), but removal at an existing iterator position is O(1); in which case your naive algorithm should be sufficiently performant.
Unless the list is a LinkedList
, the cost of shifting the list each time you call remove()
is likely one of the most expensive parts of the implementation. For array lists, I would consider using:
public static List removeMany(List items) {
List newList = new ArrayList(items.size());
Iterator iter = items.iterator();
while (iter.hasNext()) {
T item = iter.next();
// goes here
if (/*: */i++ % 2 != 0) {
newList.add(item);
}
}
return newList;
}