Copy all the elements from one set to another in Java

Java 8Object Oriented ProgrammingProgramming

Use the clone() method to copy all elements from one set to another.

First HashSet −

HashSet <String> set = new HashSet <String>();
set.add("One");
set.add("Two");

Create another set and clone first set into the second −

HashSet <String> newSet = new HashSet <String>();

Copy (clone) all elements to the second set −

newSet = (HashSet)set.clone();

The following is an example to copy all elements from one set to another −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set = new HashSet <String>();
      HashSet <String> newSet = new HashSet <String>();
      set.add("One");
      set.add("Two");
      System.out.println("Hash Set "+ set);
      newSet = (HashSet)set.clone();
      System.out.println("New Hash Set: "+ newSet);
   }
}

Output

Hash Set: [One, Two]
New Hash Set: [One, Two]
raja
Published on 30-Jan-2019 12:05:21
Advertisements