Comparing two HashSet objects using containsAll() method

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

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

 

Comparing 2 HashSet contents :

Method signature:

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

Compare2HashSetContents.java

package in.bench.resources.java.collections;

import java.util.HashSet;

public class Compare2HashSetContents {

	public static void main(String[] args) {

		// 1: creating HashSet object of type String
		HashSet<String> hset1 = new HashSet<String>();

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

		// Iterating using enhanced for-loop
		System.out.println("Iterating HashSet-1 :\n");
		for(String str : hset1) {
			System.out.println(str);
		}


		// 2: creating HashSet object of type String
		HashSet<String> hset2 = new HashSet<String>();

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

		System.out.println("\n\nHashSet-2 : " + hset2);

		// checking using containsAll() method
		System.out.println("\nwhether HashSet-1 contains all "
				+ "elements of HashSet-2 : " + hset1.containsAll(hset2));


		// 3: creating HashSet object of type String
		HashSet<String> hset3 = new HashSet<String>();

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

		System.out.println("\n\nHashSet-3 : " + hset3);

		// checking using containsAll() method
		System.out.println("\nwhether HashSet-1 contains all "
				+ "elements of HashSet-3 : " + hset1.containsAll(hset3));
	}
}

Output:

Iterating HashSet-1 :

Shantanu Narayen
Sundar Pichai
Shiv Nadar
Satya Nadella


HashSet-2 : [Sundar Pichai, Shiv Nadar, Satya Nadella]

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


HashSet-3 : [Shiv Nadar, Narayan Murthy, Satya Nadella]

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

From above example, HashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, retrieve elements in random-order

 

References:

 

Happy Coding !!
Happy Learning !!

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