Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Subtract these lists faster?

I want to subtract two ArrayLists so I can have the child that are not in the other list.

I do it this way:

removeIDs=(ArrayList<Integer>) storedIDs.clone();
removeIDs.removeAll(downloadedIDs);

downloadIDs=(ArrayList<Integer>) downloadedIDs.clone();
downloadIDs.removeAll(storedIDs);

The Problem is that both lists contain 5000childs and it takes almost 4 seconds on my androidphone.

Is there a fast way to do this? Is using sets faster?(i dont have duplicate values in the lists)

I develop an android app

like image 565
user1886411 Avatar asked Mar 12 '13 20:03

user1886411


People also ask

How do you do a subtraction list?

To perform list subtraction, the two input lists must be of the same length and it should contain elements of the same type i.e. both lists must contain only numerical values. The given example subtracts the elements at each index in one list from the other list.

How do you subtract two arrays from each other in python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.

How do you subtract two strings in a list in Python?

Method #1 : Using loop + remove() The combination of above functionalities can be used to perform this task. In this, we perform the removal of elements using remove() and check for similar elements using loop.

How do you subtract in Python?

Python Subtraction – Arithmetic OperatorPython Subtraction Operator takes two operands, first one on left and second one on right, and returns difference of the the second operand from the first operand. The symbol used for Python Subtraction operator is - .


2 Answers

Use HashSet instead of ArrayList unless you need to keep the order.

Removing an element requires a scan of the full List for list implementations, a HashSet by comparison is just the calculation of a hash code and then identification of a target bucket.

like image 191
Chris Cooper Avatar answered Sep 30 '22 16:09

Chris Cooper


Sets should be must faster. Right now, it's basically doing an n^2 loop. It loops over every element in removeIDs and checks to see if that id is in downloadedIDs, which requires searching the whole list. If downloadedIDs were stored in something faster for searching, like a HashSet, this would be much faster and become an O(n) instead of O(n^2). There might also be something faster in the Collections API, but I don't know it.

If you need to preserver ordering, you can use a LinkedHashSet instead of a normal HashSet but it will add some memory overheard and a bit of a performance hit for inserting/removing elements.

like image 32
user2144429 Avatar answered Sep 30 '22 17:09

user2144429