Converting from HashSet to String[]

前端 未结 3 1503
清歌不尽
清歌不尽 2021-02-02 06:59

What\'s the best way to convert HashSet to String[]?

相关标签:
3条回答
  • 2021-02-02 07:27

    The JB Nizet's answer is correct. In Java 15, the better answer is:

    set.toArray(new String[0]); 
    
    0 讨论(0)
  • 2021-02-02 07:29
    set.toArray(new String[set.size()]);
    
    0 讨论(0)
  • 2021-02-02 07:35

    Answer of JB Nizet is correct, but in case you did this to transform to a CSV like string, with Java 8 you can now do:

    Set<String> mySet = new HashSet<>(Arrays.asList("a", "b", "c"));
    System.out.println(String.join(", ", mySet));
    
    Output is: a, b, c
    

    This allows to bypass array notation (the []).

    0 讨论(0)
提交回复
热议问题