beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to copy one Set to another Set

By Chaitanya Singh | Filed Under: Java.util package

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]

Enjoyed this post? Try these related posts

  1. Append all the elements of a List to LinkedList – Java
  2. How to convert a HashSet to a TreeSet
  3. Convert HashSet to a List/ArrayList
  4. Adding element to front of LinkedList in Java
  5. Iterate a LinkedList in reverse sequential order – java
  6. Adding an element to LinkedList using add(E e) method – Java

Leave a Reply Cancel reply

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

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap