2

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?

6
  • Do you need random access to the list or linear access? Commented Mar 26, 2015 at 6:12
  • 1
    Share you code, how you are removing the element and what the elements are. Commented Mar 26, 2015 at 6:12
  • 1
    Provide your code...!! Commented Mar 26, 2015 at 6:13
  • You could use List#removeAll Commented Mar 26, 2015 at 6:13
  • Does it have to be an array? Or can you use other data structures? Commented Mar 26, 2015 at 6:23

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'll try using hashset as it takes o(1) for searching.
2

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...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.