Java int[] array to HashSet<Integer>
The question asks two separate questions: converting int[]
to Integer[]
and creating a HashSet<Integer>
from an int[]
. Both are easy to do with Java 8 streams:
int[] array = ...
Integer[] boxedArray = IntStream.of(array).boxed().toArray(Integer[]::new);
Set<Integer> set = IntStream.of(array).boxed().collect(Collectors.toSet());
//or if you need a HashSet specifically
HashSet<Integer> hashset = IntStream.of(array).boxed()
.collect(Collectors.toCollection(HashSet::new));
Using Stream:
// int[] nums = {1,2,3,4,5}
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet())
Some further explanation. The asList method has this signature
public static <T> List<T> asList(T... a)
So if you do this:
List<Integer> list = Arrays.asList(1, 2, 3, 4)
or this:
List<Integer> list = Arrays.asList(new Integer[] { 1, 2, 3, 4 })
In these cases, I believe java is able to infer that you want a List back, so it fills in the type parameter, which means it expects Integer parameters to the method call. Since it's able to autobox the values from int to Integer, it's fine.
However, this will not work
List<Integer> list = Arrays.asList(new int[] { 1, 2, 3, 4} )
because primitive to wrapper coercion (ie. int[] to Integer[]) is not built into the language (not sure why they didn't do this, but they didn't).
As a result, each primitive type would have to be handled as it's own overloaded method, which is what the commons package does. ie.
public static List<Integer> asList(int i...);