I have two arrayLists and I am trying to \"subtract\" one arrayList from another. For example, if I have one arrayList [1,2,3] and I am trying to subtract [0, 2, 4] the resu
Your problem is that in your minusArray.remove(...) call you may shrink the size of the minusArray. To fix this, start at array.size() - 1 and count backwards to 0
Check that - even that won't fix it. You need to reverse the order of your loops
Try this answer if
removeAll()
is not what you want. e.g. if you are interested in something like Calculating difference of two lists with duplicates
subtract(a,b)
b.forEach((i)->a.remove(i));
a
now contains
[1, 3]
This follows the suggestion of Guava implementors on how to implement subtract
"create an ArrayList containing a and then call remove on it for each element in b."
Which behaves like this implementation used in Apache commons
Difference to removeAll()
[1,2,2,3].removeAll([1,2,3]) //is empty
[1,2,3].forEach((i)->[1,2,2,3].remove(i)); //a is [2]
My parameterized solution would be like:
<T> ArrayList<T> subtract(ArrayList<T> alpha, ArrayList<T> beta) {
ArrayList<T> gamma = new ArrayList<T>();
alpha.forEach(n -> {if (!beta.contains(n)) gamma.add(n); });
return gamma;
}
Traversing the minusArray
using an index is one way to do this, but I suggest you make use of the contains(Object)
method, which will allow you then to use remove(Object)
for the particular element of array2
.
Of course, there's always the removeAll(Collection)
which does pretty much everything you need...
You can use org.apache.commons.collections.ListUtils and make all that you want in only one line =)
List resultList = ListUtils.subtract(list, list2);
I'm guessing you get the range problem because you've eliminated one of the elements which changes what the inner loop is looking for (I know this problem occurs when dealing with normal Lists and Collections).
What I've had to do in the past to work around this, is to create a list of items that need to be removed (that is ones that are found in the original list). Iterate through that new list and directly eliminate the original list's elements without having to have an iterator moving through it.