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 291 views
291 views asked Jan 16, 2022 by avibootz
1 answer 222 views
222 views asked Jul 23, 2023 by avibootz
1 answer 192 views
192 views asked Jul 22, 2023 by avibootz
1 answer 212 views
1 answer 213 views
2 answers 392 views
3 answers 254 views
254 views asked Jul 6, 2025 by avibootz
...