Adding one HashSet to another HashSet using addAll() method

In this article, we will add one HashSet contents to another HashSet using addAll method of Collection interface

 

Adding one HashSet to another HashSet :

Method signature:

boolean addAll(Collection c);
  • This method is used to add one HashSet contents to another HashSet contents
  • Returns true, if this set changed as a result of the call

AddOneHashSetToAnotherHashSet.java

package in.bench.resources.java.collections;

import java.util.HashSet;

public class AddOneHashSetToAnotherHashSet {

	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 original 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("Narayan Murthy"); 
		hset2.add("Nandan Nilekeni");
		hset2.add("Shibulhset SD");

		boolean boolAddAll = hset1.addAll(hset2);
		System.out.println("\n\nWhether invoking HashSet-1 "
				+ "changed : " + boolAddAll);

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating after addAll operation\n");
		for(String str : hset1) {
			System.out.println(str);
		}
	}
}

Output:

Iterating original HashSet-1

Shantanu Narayen
Shiv Nadar
Sundar Pichai
Satya Nadella


Whether invoking HashSet-1 changed : true


Iterating after addAll operation

Shantanu Narayen
Shiv Nadar
Sundar Pichai
Nandan Nilekeni
Shibulhset SD
Satya Nadella
Narayan Murthy

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 !!

Various ways to iterate through HashSet - 3 ways
Comparing two HashSet objects using containsAll() method