Comparing two ArrayList objects using containsAll() method

In this article, we will compare 2 ArrayList contents using containsAll method of Collection interface

This Collection method is used to check whether one list contents contains all elements in another list contents

 

Comparing 2 ArrayList contents using containsAll() method :

Method signature:

boolean containsAll(Collection<?> c);
  • This method is used to compare one ArrayList contents with another ArrayList contents
  • Returns true, if all elements present;
  • otherwise return false

Compare2ArrayListContents.java

package in.bench.resources.java.collections;

import java.util.ArrayList;

public class Compare2ArrayListContents {

	public static void main(String[] args) {

		// 1: creating ArrayList object of type String
		ArrayList<String> al1 = new ArrayList<String>();

		// adding elements to ArrayList object
		al1.add("Sundar Pichai");
		al1.add("Satya Nadella");  
		al1.add("Shiv Nadar");  
		al1.add("Shantanu Narayen");

		// Iterating using enhanced for-loop
		System.out.println("Iterating "
				+ "ArrayList using enhanced for-loop\n");
		for(String str : al1) {
			System.out.println(str);
		}


		// 2: creating ArrayList object of type String
		ArrayList<String> al2 = new ArrayList<String>();

		// adding elements to ArrayList object
		al2.add("Satya Nadella"); 
		al2.add("Sundar Pichai");
		al2.add("Shiv Nadar");  

		System.out.println("\n\nwhether ArrayList-1 contains "
				+ "all elements of ArrayList-2 : "
				+ al1.containsAll(al2));


		// 3: creating ArrayList object of type String
		ArrayList<String> al3 = new ArrayList<String>();

		// adding elements to ArrayList object
		al3.add("Satya Nadella"); 
		al3.add("Narayan Murthy");
		al3.add("Shiv Nadar");  

		System.out.println("\n\nwhether ArrayList-1 contains "
				+ "all elements of ArrayList-3 : "
				+ al1.containsAll(al3));
	}
}

Output:

Iterating ArrayList using enhanced for-loop

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen


whether ArrayList-1 contains all elements of ArrayList-2 : true


whether ArrayList-1 contains all elements of ArrayList-3 : false

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion-order is maintained

 

References:

 

Happy Coding !!
Happy Learning !!

Adding one ArrayList to another ArrayList using addAll() method
How to check whether particular element is present in ArrayList