Java int[] array to HashSet<Integer>

Viewed 81285

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!

8 Answers

Using Stream:

// int[] nums = {1,2,3,4,5}
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet())

Just add elements from array to Set with the below snippet

public class RemoveDuplicateElements {

    public static void main(String args[]){
        int array[] =  {0,1,2,3,4,5,6,7,8,9,1,2,3,4,5};
        Set <Integer> abc = new HashSet <Integer>();
        for (Integer t:array){  
            abc.add(t); 
        }       
        System.out.println("sampleSet"+abc);  
    }

}

No need for looping :
Just you will convert the array to a List
Then converting this List to a hash set.
Ex:
List list = Arrays.asList(your_array);
Set set = new HashSet<>(list);


This worked perfect for me .

Related