Add all the elements from a collection to the HashSet in Java


First, set the collection −

String strArr[] = { "P", "Q", "R", "S" };

Now, take a Set and add all the elements of the above collection using asList() method −

Set s = new HashSet(Arrays.asList(strArr));

The following is an example to add all elements from a collection to the HashSet −

Example

 Live Demo

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      String strArr[] = { "P", "Q", "R", "S" };
      Set s = new HashSet(Arrays.asList(strArr));
      strArr = new String[] { "R", "S", "T", "U" };
      s.addAll(Arrays.asList(strArr));
      strArr = new String[] { "S", "T", "U" };
      s.addAll(Arrays.asList(strArr));
      System.out.println(s);
   }
}

Output

[P, Q, R, S, T, U]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

341 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements