Convert Array to 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]
Updated on: 2019-07-30T22:30:20+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements