Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java int[] array to HashSet<Integer>

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" })); 

How to easily, correctly and succinctly go from:

A) int[] a... 

to

B) Integer[] a ... 

Thanks!

like image 520
Robottinosino Avatar asked Aug 19 '12 23:08

Robottinosino


People also ask

Can we convert array to HashSet in Java?

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.

Can we convert array to set Java?

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.

How do you convert an array of integers into a single integer in Java?

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.


2 Answers

Using Stream:

// int[] nums = {1,2,3,4,5} Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet()) 
like image 105
Liam.Nguyen Avatar answered Sep 18 '22 21:09

Liam.Nguyen


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)); 
like image 36
Jeffrey Bosboom Avatar answered Sep 19 '22 21:09

Jeffrey Bosboom