Convert elements in a HashSet to an array in Java

Java 8Object Oriented ProgrammingProgramming

First, create a HashSet and elements to it −

HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("K");

Let us now convert the above HashSet to an array −

Object[] ob = hs.toArray();

The following is an example to convert elements in a HashSet to an array −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create a hash set
      HashSet hs = new HashSet();
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      hs.add("K");
      hs.add("M");
      hs.add("N");
      System.out.println("Elements in the set: "+hs);
      Object[] ob = hs.toArray();
      System.out.println("Converting elements to array...");
      for (int i = 0; i < ob.length; i++) {
         System.out.println(ob[i]);
      }
   }
}

Output

Elements in the set: [A, B, C, D, E, F, K, M, N]
Converting elements to array...
A
B
C
D
E
F
K
M
N
raja
Published on 11-Jan-2019 16:53:26
Advertisements