How to Merge two HashSets in Java

In this article we will discuss how to merge two HashSets.

HashSet provides a member function addAll() i.e.

public boolean addAll(Collection<? extends E> c)

It provides a functionality to add a collection into to a HashSet. But this Collection should be of Same Type as of HashSet or of its Base Class.

How addAll() works

It will iterate over the given Collection one by one and add each element individually in the Hashset. Also, if it has added any element then it will return true else returns false.

Let’s see how to merge to HashSets i.e.

package com.thispointer.java.collections.hashsets;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;

public class Example3 {

	public static void main(String[] args) {
		
		// Create a new HashSet of String objects
		HashSet<String> setOfStrs1 = new HashSet<>();
		
		// Adding elements in HashSet
		setOfStrs1.add("hello");
		setOfStrs1.add("abc");
		setOfStrs1.add("time");
		setOfStrs1.add("Hi");
		
		System.out.println("setOfStrs1 = " + setOfStrs1);
		
		// Create a new HashSet of String objects
		HashSet<String> setOfStrs2 = new HashSet<>();
		
		// Adding elements in HashSet
		setOfStrs2.add("this");
		setOfStrs2.add("that");
		setOfStrs2.add("there");
	
		System.out.println("setOfStrs2 = " + setOfStrs2);

		// Merge Set 2 in Set 1
		boolean bResult = setOfStrs1.addAll(setOfStrs2);
				
		if(bResult)
		{
			System.out.println("Merging of Set 1 & Set 2 Successfull");
		}
		
		System.out.println("setOfStrs1 = " + setOfStrs1);
		
	}

}

Output:

setOfStrs1 = [Hi, abc, hello, time]
setOfStrs2 = [that, there, this]
Merging of Set 1 & Set 2 Successfull
setOfStrs1 = [Hi, that, abc, there, this, hello, time]

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top