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 201 views
201 views asked Jan 16, 2022 by avibootz
1 answer 134 views
134 views asked Jul 23, 2023 by avibootz
1 answer 113 views
113 views asked Jul 22, 2023 by avibootz
1 answer 133 views
1 answer 133 views
2 answers 287 views
3 answers 121 views
121 views asked Jul 6, 2025 by avibootz
...