In this article we are gonna see an example program to copy one Set to another Set.
Example
In this example we are copying one HashSet to another HashSet, however you can use any other Set like TreeSet, LinkedHashSet etc in the same manner as shown below.
import java.util.HashSet; class CopySetExample{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Element1"); hset.add("Element2"); hset.add("Element3"); System.out.println("Set before addAll:"+ hset); // Create another HashSet HashSet<String> hset2 = new HashSet<String>(); hset2.add("Item1"); hset2.add("Item2"); // Copying one Set to another hset.addAll(hset2); System.out.println("Set after addAll:"+ hset); } }
Output:
Set before addAll:[Element1, Element2, Element3] Set after addAll:[Item1, Item2, Element1, Element2, Element3]
Leave a Reply