JAVA HashSet addAll Method Example

JAVA Util Package provides various implementation for collections. Set interface is a part of this Util Package. HashSet is an implementation of this Set interface. Other implementation of Set interface is TreeSet.

In this tutorial, we will learn about JAVA HashSet addAll method and its use in programming.

JAVA HashSet add method Example:

package com.Jwalant;

import java.util.HashSet;

public class HashSetAddExample {

  public static void main(String[] args) {
		
		Set<String> firstSet = new HashSet<String>();
		
		firstSet.add("USA");
		firstSet.add("CANADA");
		firstSet.add("U.K.");
		firstSet.add("INDIA");
		
		Set<String> secondSet = new HashSet<String>();
		
		secondSet.add("USA");
		secondSet.add("CANADA");
		secondSet.add("Italy");
		secondSet.add("Brazil");
		
		boolean result = firstSet.addAll(secondSet);
		System.out.println("Any element added ? "+result);
		
		System.out.println("Size of set "+firstSet.size());
		for(String country : firstSet) {
			System.out.println("Country "+country);
		}
  }
}

Output: 

Any element added ? true

Size of set 6

Country CANADA

Country USA

Country Brazil

Country INDIA

Country U.K.

Country Italy


Return Type: Boolean

As you can see above, addAll() method of HashSet class adds all elements from one set to another set. If atleaset one unique element is added, it returns true. 

comments powered by Disqus