Java – 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

1. Adding one HashSet to another HashSet :

  • 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

Method signature:

boolean addAll(Collection c);

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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Iterate through HashSet in 3 ways
Java - Comparing two HashSet objects using containsAll() method