Open In App

AbstractCollection containsAll() Method in Java

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The containsAll() method of Java AbstractCollection is used to check whether a collection contains all elements of another collection.

Example 1: This program checks if two collections have the same elements using AbstractCollection.containsAll() method.

Java
// Java Program to illustrate containsAll() method
import java.util.*; 

class Geeks
{ 
	public static void main(String args[]) 
	{ 
		// Creating an empty Collection 
		AbstractCollection<String> 
		abs = new LinkedList<String>(); 

		// Use add() method to 
		// add elements in the collection 
		abs.add("Geeks"); 
		abs.add("for"); 
		abs.add("Geeks"); 
		abs.add("10"); 
		abs.add("20"); 

		// Creating another empty Collection 
		AbstractCollection<String> 
		abs2 = new LinkedList<String>(); 

		// Use add() method to 
		// add elements in the collection 
		abs2.add("Geeks"); 
		abs2.add("for"); 
		abs2.add("Geeks"); 
		abs2.add("10"); 
		abs2.add("20"); 

		// Check if the collection 
		// contains same elements 
		System.out.println("Both the collections same: "
		+ abs.containsAll(abs2)); 
	} 
} 

Output
Both the collections same: true

Explanation: In the above example, we create two collections (abs and abs2) and the same elements for both. Then we use the containsAll() method to check if abs contain all the elements from abs2. It returns true because both collections have the same element.

Syntax of AbstractCollection.containsAll()

boolean containsAll(Collection<?> c);

  • Parameters: The parameter C is a Collection refers to the collection whose elements occurrence needs to be checked in this collection.
  • Return Value: The method returns True if this collection contains all the elements of other Collections otherwise it returns False.

Example 2: Here is another example demonstrating the containsAll() method with different elements.

Java
// Java Program to illustrate boolean containsAll() 
import java.util.*; 

class Geeks 
{
	public static void main(String args[]) 
	{ 
		// Creating an empty Collection 
		AbstractCollection<String> 
		abs = new LinkedList<String>(); 

		// Use add() method to 
		// add elements in the collection 
		abs.add("Geeks"); 
		abs.add("for"); 
		abs.add("Geeks"); 

		// Creating another empty Collection 
		AbstractCollection<String> 
		abs2 = new LinkedList<String>(); 

		// Use add() method to 
		// add elements in the collection 
		abs2.add("10"); 
		abs2.add("20"); 

		// Check if the collection 
		// contains same elements 
		System.out.println("Both the collections same: "
		+ abs.containsAll(abs2)); 
	} 
} 

Output
Both the collections same: false

Explanation: In this example, we have two different collections having different elements that’s why it returns false.



Next Article

Similar Reads