Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Set<Integer> to a primitive array [duplicate]

I am using the following code to convert a Set to int[]

Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();

the I got the following error:

 error: incompatible types: Object[] cannot be converted to int[]

What would be the most clean way to do the conversion without adding element one by one using a for loop? Thanks!

like image 227
Edamame Avatar asked Dec 02 '22 14:12

Edamame


2 Answers

You usually do this:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();
like image 121
xehpuk Avatar answered Dec 15 '22 05:12

xehpuk


Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);
like image 34
s7vr Avatar answered Dec 15 '22 05:12

s7vr