We can use addAll() method to copy set content to another hashset in java.
Syntax:
hashSet.addAll(subSet);
Example:
package com.w3schools; import java.util.HashSet; public class Test { public static void main(String[] args) { //Create HashSet object HashSet<String> hashSet = new HashSet<String>(); //Add elements to HashSet hashSet.add("Jai"); hashSet.add("Mahesh"); hashSet.add("Vivek"); hashSet.add("Naren"); hashSet.add("Vishal"); hashSet.add("Hemant"); System.out.println("HashSet: " + hashSet); HashSet<String> subSet = new HashSet<String>(); subSet.add("Sachin"); subSet.add("Sahil"); hashSet.addAll(subSet); System.out.println("HashSet after modification: " + hashSet); } } |
Output
HashSet: [Naren, Jai, Vivek, Hemant, Mahesh, Vishal] HashSet after modification: [Naren, Sahil, Jai, Vivek, Hemant, Mahesh, Vishal, Sachin] |