How to convert HashSet to Array in Java

1 Answer

0 votes
import java.util.Set;
import java.util.Arrays;
import java.util.HashSet;

public class MyClass {
    public static void main(String args[]) {
        Set<String> hset = new HashSet<>();
        
        hset.add("java");
        hset.add("c");
        hset.add("c++");
        hset.add("c#");
        hset.add("python");
        
        String[] array = new String[hset.size()];
        hset.toArray(array);

        System.out.println(Arrays.toString(array));
    }
}



 
/*
run:
    
[c#, c++, python, java, c]
  
*/

 



answered Jan 16, 2022 by avibootz

Related questions

1 answer 294 views
294 views asked Jan 16, 2022 by avibootz
1 answer 223 views
223 views asked Jul 23, 2023 by avibootz
1 answer 193 views
193 views asked Jul 22, 2023 by avibootz
1 answer 213 views
1 answer 214 views
2 answers 393 views
3 answers 254 views
254 views asked Jul 6, 2025 by avibootz
...