Using Stream:
// int[] nums = {1,2,3,4,5}
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet())
Answer from Liam.Nguyen on Stack OverflowUsing Stream:
// int[] nums = {1,2,3,4,5}
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet())
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));
java - How to convert a set of Integers to an int[] array? - Stack Overflow
How can I convert a Java HashSet to a primitive int array? - Stack Overflow
Cannot convert array to set in java. Getting error
set method for an array
Videos
string[] doesn't exist, I guess you mean String[].
For converting a Set<Integer> to int[] you'd have to iterate over the set manually.
Like this:
Set<Integer> set = ...;
int[] arr = new int[set.size()];
int index = 0;
for( Integer i : set ) {
arr[index++] = i; //note the autounboxing here
}
Note that sets don't have any particular order, if the order is important, you'd need to use a SortedSet.
This is why Guava has an Ints.toArray(Collection<Integer>) method, returning int[].
You can create an int[] from any Collection<Integer> (including a HashSet<Integer>) using Java 8 streams:
int[] array = coll.stream().mapToInt(Number::intValue).toArray();
The library is still iterating over the collection (or other stream source) on your behalf, of course.
In addition to being concise and having no external library dependencies, streams also let you go parallel if you have a really big collection to copy.
Apache's ArrayUtils has this (it still iterates behind the scenes):
doSomething(ArrayUtils.toPrimitive(hashset.toArray()));
They're always a good place to check for things like this.