How to efficiently (performance) remove many items from List in Java?

后端 未结 12 648
迷失自我
迷失自我 2021-01-31 09:00

I have quite large List named items (>= 1,000,000 items) and some condition denoted by that selects items to be deleted and is true for many (maybe hal

12条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 09:34

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

提交回复
热议问题