Convert array to HashSet in Java


Create an array and convert it to List −

Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
List<Integer> l = Arrays.asList(arr);

Now, let us convert the above array to HashSet −

Set<Integer> s = new HashSet<Integer>(l);

The following is an example to convert array to HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
      List<Integer> l = Arrays.asList(arr);
      Set<Integer> s = new HashSet<Integer>(l);
      for (Iterator i = s.iterator(); i.hasNext();) {
         Object ele = i.next();
         System.out.println(ele);
      }
   }
}

Output

35
20
40
10
30
15

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements