Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two arraylist?

Tags:

java

android

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.

like image 837
SuReSh PaTi Avatar asked Dec 21 '11 11:12

SuReSh PaTi


People also ask

Can we compare two ArrayList?

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.

How do you compare 2 arrays in Java?

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.

Can we compare array with ArrayList?

Yes, you can iterate through the array and arraylist and compare elements. ArrayList elements are accessed with . get(index) .


3 Answers

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);
like image 158
dku.rajkumar Avatar answered Oct 16 '22 07:10

dku.rajkumar


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++;
    }
}
like image 40
JB Nizet Avatar answered Oct 16 '22 09:10

JB Nizet


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); 
like image 1
Kamran Ali Avatar answered Oct 16 '22 07:10

Kamran Ali