Reputation: 295
I am using the arrayList.remove(index) function. I want to remove 40320 elements from array and it will be done 9 times in my program execution . It's taking so much time. This causes my program execution to be slow. Is there any efficient method to do that?
Upvotes: 2
Views: 3998
Reputation: 2092
With Java 8 you could use streams (even parallel streams) like this:
List<YourType> theFilteredList = theList.parallelStream()
.filter(yourPredicate)
.collect(Collectors.toList());
This will take advantage of the number of cores in your computer. With big datasets the performance increase will be significant.
Be careful with the predicate. It should be written in functional style, meaning you should not change other object's states!
And you can choose to use a lambda function as your predicate. Not sure if this will improve performance even more...
Upvotes: 2
Reputation: 7494
If you have to use an ArrayList, then each remove operation has an efficiency of O(n) as the list has to be resized every time you remove an element. If you can work with linear access to the list then I suggest you use the LinkedList data structure. But be aware that this will increase lookup times.
If you will not be iterating over the elements and you need to only know if the elements are present, then HashSet should do it.
Upvotes: 3
Reputation: 172398
You can use the listIterator like this:
for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();)
{
if (itemsToDelete(iter.previous())) iter.remove();
}
Or as MadProgrammer suggested you can use the removeAll()
method passing the ArrayList with the objects to be deleted.
As far as the time complexity of the Remove
method is concerned it is O(n)
as you have to shuffle the elements above that point "left" by one.
Upvotes: 0