57

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!

Robottinosino
  • 10,384
  • 17
  • 59
  • 97
  • 1
    Possible duplicate of: http://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java – David B Aug 19 '12 at 23:09

8 Answers8

67

Using Stream:

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

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));
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
  • I think it would be worthwhile to mention this line technique is slower. I used `IntStream.of(nums).boxed().collect(Collectors.toSet())` instead of just looping over the elements, which increased my runtime from 18ms to 25ms, on average. – Janac Meena Jun 19 '20 at 17:44
10

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...);
Matt
  • 11,523
  • 2
  • 23
  • 33
4

Or you could easly use Guava to convert int[] to List<Integer>:

Ints.asList(int...)

asList

public static List<Integer> asList(int... backingArray)

Returns a fixed-size list backed by the specified array, similar to Arrays.asList(Object[]). The list supports List.set(int, Object), but any attempt to set a value to null will result in a NullPointerException.

The returned list maintains the values, but not the identities, of Integer objects written to or read from it. For example, whether list.get(0) == list.get(0) is true for the returned list is unspecified.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
dantuch
  • 9,123
  • 6
  • 45
  • 68
2

You can use ArrayUtils in Apache Commons:

int[] intArray  = { 1, 2, 3 };
Integer[] integerArray = ArrayUtils.toObject(intArray);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    If Commons has a method to do this, it means there wasn't a way to do it with the base JDK... thanks for the pointer! – Robottinosino Aug 19 '12 at 23:28
  • Commons library takes up a lot of method references on Android, it's highly recommended to avoid using it. This makes sense and works well with ordinary Java. – milosmns Oct 03 '16 at 11:43
  • Apache Commons link is not working.....and how to use arrayUtils? – Anjan Biswas Jul 20 '22 at 18:12
1

Another option would be to use a primitive set from Eclipse Collections. You can easily convert an int[] to a MutableIntSet to a Set<Integer> or Integer[] as shown below, or you can use the MutableIntSet as is which will be much more memory efficient and performant.

int[] a = {1, 2, 3};
MutableIntSet intSet = IntSets.mutable.with(a);
Set<Integer> integerSet = intSet.collect(i -> i);  // auto-boxing
Integer[] integerArray = integerSet.toArray(new Integer[]{});

If you want to go directly from the int array to the Integer array and preserve order, then this will work.

Integer[] integers = 
        IntLists.mutable.with(a).collect(i -> i).toArray(new Integer[]{});

Note: I am a committer for Eclipse Collections

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
0

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

}
Ben
  • 740
  • 1
  • 14
  • 29
Anantha
  • 9
  • 1
-1

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 .

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 17 '22 at 01:22
  • this code is not working. – Anjan Biswas Jul 20 '22 at 18:05