Zcopy.site

Java将Set转换为数组的方法

我们可以使用以下两种方法将Set转换为数组:

  • Set.toArray()方法
  • Stream(在Java8中引入)

文件:SetToArrayExample.java -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetToArrayExample {
public static void main(String[] args) {
//List to be converted into array
Set<String> set=new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");


/*Method - 1 (Set.toArray())*/
String[] array1=set.toArray(new String[set.size()]);
System.out.println("Method -1 Output:");
for (String string : array1) {
System.out.println(string);
}

/*Method - 2 (Using stream)*/
String[] array2=set.stream().toArray(String[]::new);
System.out.println("Method -2 Output:");
for (String string : array2) {
System.out.println(string);
}
}
}

执行上面示例代码,得到以下结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
Method -1 Output:
A
B
C
D
E

Method -2 Output:
A
B
C
D
E