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

后端 未结 12 641
迷失自我
迷失自我 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:41

    I would make a new List to add the items to, since removing an item from the middle of a List is quite expensive.

    public static List removeMany(List items) {
        List tempList = new ArrayList(items.size()/2); //if about half the elements are going to be removed
        Iterator iter = items.iterator();
        while (item : items) {
            //  goes here
            if (/*: */i % 2 != 0) {
                tempList.add(item);
            }
        }
        return tempList;
    }
    

    EDIT: I haven't tested this, so there may very well be small syntax errors.

    Second EDIT: Using a LinkedList is better when you don't need random access but fast add times.

    BUT...

    The constant factor for ArrayList is smaller than that for LinkedList (Ref). Since you can make a reasonable guess of how many elements will be removed (you said "about half" in your question), adding an element to the end of an ArrayList is O(1) as long as you don't have to re-allocate it. So, if you can make a reasonable guess, I would expect the ArrayList to be marginally faster than the LinkedList in most cases. (This applies to the code I have posted. In your naive implementatation, I think LinkedList will be faster).

提交回复
热议问题