I have an array of int:
int[] a = {1, 2, 3};
I need a typed set from it:
Set<Integer> s;
If I do the following:
s = new HashSet(Arrays.asList(a));
it, of course, thinks I mean:
List<int[]>
whereas I meant:
List<Integer>
This is because int is a primitive. If I had used String, all would work:
Set<String> s = new HashSet<String>( Arrays.asList(new String[] { "1", "2", "3" }));
A) int[] a...
to
B) Integer[] a ...
Thanks!
To convert array to set , we first convert it to a list using asList() as HashSet accepts a list as a constructor. Then, we initialize the set with the elements of the converted list.
Converting an array to Set objectThe Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.
We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.
Using 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With