How to copy Set content to another HashSet?

In this tutorial we will see how to copy element of one set to hashset. addAll() method can copy any collection to hashset . Let’s see this by code

import java.util.HashSet;
import java.util.Set;

public class AddAll {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");

// print hashset
System.out.println("hs is = " + hs);

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

/*
* Adds all of the elements in the specified
*  collection to hashset collection
*/

hashSet.addAll(hs);

System.out.println("hashset is="+hashSet);

}

}

Output:

hs is = [javascript, php, html, java, mysql]

hashset is=[javascript, php, java, html, mysql]

 A Guide To Hashset                                                                                                             A Guide To Collection in Java                                                                                             Java Doc -HashSet

Leave a Reply

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

67 − = 62