Convert array to HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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