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

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 10-Jan-2019 09:28:58
Advertisements