I have two ArrayList
. Each is of size 100000. I want to compare them and count matched elements.
Here's my code:
for (int i = 0; i < mArryLst2.size(); i++) {
if (ArryLst1.contains(mArryLst2.get(i))) {
matchedPixels++;
}
}
Here comparison process is taking lot of time.
How to solve and optimize this problem.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
Yes, you can iterate through the array and arraylist and compare elements. ArrayList elements are accessed with . get(index) .
you should use CollectionUtils.retainAll
: Returns a collection containing all the elements in collection1 that are also in collection2.
ArrayList commonList = CollectionUtils.retainAll(list1,list2);
You should transform you first list into a HashSet. HashSet lookups are O(1), and List lookups are O(n). This makes the whole algorithm O(n) rather than O(n^2)
Set<Foo> set1 = new HashSet<Foo>(list1);
for (Foo foo : list2) {
if (set1.contains(foo)) {
matchedPixels++;
}
}
you should look at this link How to compare two Arraylist values in java?. make a copy of one of the list and then call remove all for the list against the other list
List result = new ArrayList(mArryLst2);
result.removeAll(ArryLst1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With