How to convert an Array to a Set in Java?


One solution to add an array to set is to use the addAll() method of the Collections class. This method accepts a collection and an element and, it adds the given element to the specified Collection.

Example

Live Demo
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class ArrayToSet {
   public static void main(String args[]) {
      Integer[] myArray = {23, 93, 56, 92, 39};
      Set<Integer> set = new HashSet<Integer>();
      Collections.addAll(set, myArray);
      System.out.println(set);
   }
}

Output

[23, 39, 56, 92, 93]

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements