将Set <Integer>转换为基本数组

Eda*_*ame 0 java collections set data-structures

我使用以下代码将Set转换为int []

Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

 error: incompatible types: Object[] cannot be converted to int[]
Run Code Online (Sandbox Code Playgroud)

在没有使用for循环逐个添加元素的情况下进行转换最干净的方法是什么?谢谢!

use*_*814 6

Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);
Run Code Online (Sandbox Code Playgroud)


xeh*_*puk 5

你经常这样做:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1953 次

最近记录:

9 年,6 月 前