Compare two arrayLists in java

In the previous post, we have seen how to find out first and last occurrence of elements in arrayList. In this post , we will see how to compare two arrayLists in java.

We use the method named as ‘contains’ to check the existence of element present in the array list. It returns boolean value i.e. true/false. Therefore, we an use it to compare two arrayList. Let’s understand this with an example.

Syntax:

public boolean contains(Object o)

Example:

import java.util.ArrayList;

public class ArrayListEx {

	public static void main(String[] args) {
		ArrayList<String> fruits1 = new ArrayList<String>();
		fruits1.add("Orange");
		fruits1.add("Mango");
		fruits1.add("Apple");
		fruits1.add("Grapes");
		fruits1.add("Banana");
		fruits1.add("Apple");
		fruits1.add("Orange");
		fruits1.add("Orange");
		
		ArrayList<String> fruits2 = new ArrayList<String>();
		fruits2.add("Papaya");
		fruits2.add("Mango");
		fruits2.add("Blueberry");
		fruits2.add("Grapes");
		fruits2.add("Banana");
		fruits2.add("Apple");
		fruits2.add("Dates");
		fruits2.add("Orange");
		System.out.println("Total fruits: "+fruits2.size());
		
		for(int i=0;i<fruits1.size();i++){
			if(fruits1.contains(fruits2.get(i))){
				System.out.println("Exist : "+fruits2.get(i));
			}else{
				System.out.println("Not Exist : "+fruits2.get(i));
			}
		}
	}
}

Output:

Total fruits: 8
Not Exist : Papaya
Exist : Mango
Not Exist : Blueberry
Exist : Grapes
Exist : Banana
Exist : Apple
Not Exist : Dates
Exist : Orange


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...