564

How do I convert int[] into List<Integer> in Java?

Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the best to show the fact that this functionality is not part of Java.

Jonik
  • 80,077
  • 70
  • 264
  • 372
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

21 Answers21

556

Streams

  1. In Java 8+ you can make a stream of your int array. Call either Arrays.stream or IntStream.of.
  2. Call IntStream#boxed to use boxing conversion from int primitive to Integer objects.
  3. Collect into a list using Stream.collect( Collectors.toList() ). Or more simply in Java 16+, call Stream#toList().

Example:

int[] ints = {1,2,3};
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

In Java 16 and later:

List<Integer> list = Arrays.stream(ints).boxed().toList();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
mikeyreilly
  • 6,523
  • 1
  • 26
  • 21
  • 27
    Equivalent to: Arrays.stream(ints).boxed().collect(Collectors.toList()); – njfrost Jul 01 '16 at 17:12
  • 4
    @njfrost You're right and IntStream.of just calls Arrays.stream so I've improved the answer following your suggestion – mikeyreilly Oct 04 '17 at 08:00
  • 2
    For some reason this doesn't seem to be returning the expected result type on Android Studio(works on eclipse) It says, expected List found List. – Eugenio Lopez Aug 07 '18 at 19:13
  • 2
    It looks clean and concise but when I used this as opposed to the basic solution provided by @willcodejavaforfood on leetcode the program performance degraded in terms of memory as well as runtime – chitresh sirohi Mar 31 '20 at 03:31
  • 1
    @chitreshsirohi that is because lambda functions used inside streams result in Java to make some anonymous classes. – Ashvin Sharma Jun 02 '20 at 03:44
  • This solution is little complex to me. ------- I use bellow solution ----------------------- int[] ints = {1, 2, 3}; List intList = new ArrayList(ints.length); for (int i : ints) { intList.add(i); } If we talks about complexity, then which one is batter? – Anjan Biswas Jul 20 '22 at 18:49
  • `IntStream.of(array).boxed().collect(Collectors.toList());` – Zon Oct 13 '22 at 14:27
  • Why does `Arrays.asList(arr)` evidently return a list of a single element, the `arr` array? I thought converting an array to an `ArrayList` is as simple as `new ArrayList(Arrays.asList(arr))` – Sergey Zolotarev Feb 19 '23 at 13:21
  • I am getting code sonar issue i.e "Closeable Not Stored(Java)". Is there any way we can avoid this sonar issue? – Ram Chaithanya Feb 23 '23 at 10:59
346

There is no shortcut for converting from int[] to List<Integer> as Arrays.asList does not deal with boxing and will just create a List<int[]> which is not what you want. You have to make a utility method.

int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
    intList.add(i);
}
Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
194

Also from guava libraries... com.google.common.primitives.Ints:

List<Integer> Ints.asList(int...)
iraSenthil
  • 11,307
  • 6
  • 39
  • 49
louisgab
  • 2,414
  • 1
  • 15
  • 9
  • 13
    This one should be the right answer. See the second sentence of the question: "Of course, I'm interested in any other answer than doing it in a loop, item by item." – josketres Apr 22 '14 at 12:22
  • 3
    There are a few subtleties here. The returned list uses the provided array as backing store, so you should not mutate the array. The list also doesn't guarantee identity of the contained Integer objects. That is, the result of list.get(0) == list.get(0) is not specified. – pburka Apr 22 '15 at 15:45
  • 1
    Beware of the method reference count on Android when adding libraries. Good find though. – milosmns Oct 03 '16 at 13:39
  • In Android I had to add `implementation 'com.google.firebase:firebase-crashlytics-buildtools:2.9.0'` to build.gradle for this to work. – Donald Duck Jun 05 '22 at 10:02
116

Arrays.asList will not work as some of the other answers expect.

This code will not create a list of 10 integers. It will print 1, not 10:

int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());

This will create a list of integers:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

If you already have the array of ints, there is not quick way to convert, you're better off with the loop.

On the other hand, if your array has Objects, not primitives in it, Arrays.asList will work:

String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
Leonel
  • 28,541
  • 26
  • 76
  • 103
  • 10
    Do note, that that list is immutable – Danielson Sep 21 '18 at 16:22
  • 4
    Arrays.asList(arr) in the above comment will generate a list of type List which is incompatible with List. If one were to try to assign the output to a variable like so ``` List l = Arrays.asList(arr); ``` you'd get the following error | Error: | incompatible types: inference variable T has incompatible bounds | equality constraints: java.lang.Integer | lower bounds: int[] | List l = Arrays.asList(a); | ^--------------^ – Vishal Seshagiri Jan 09 '21 at 15:46
  • 1
    this is wrong! it generates List – d2k2 Jan 12 '23 at 12:02
55

I'll add another answer with a different method; no loop but an anonymous class that will utilize the autoboxing features:

public List<Integer> asList(final int[] is)
{
    return new AbstractList<Integer>() {
            public Integer get(int i) { return is[i]; }
            public int size() { return is.length; }
    };
}
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Christoffer
  • 12,712
  • 7
  • 37
  • 53
  • 1
    +1 this is shorter than mine but mine works for all primitives types – dfa Jul 02 '09 at 12:31
  • 7
    While quicker and using less memory than creating an ArrayList, the trade off is List.add() and List.remove() don't work. – Stephen Denne Jul 02 '09 at 13:03
  • 3
    I quite like this solution for large arrays with sparse access patterns but for frequently accessed elements it would result in many unnecessary instantiations of Integer (e.g. if you accessed the same element 100 times). Also you would need to define Iterator and wrap the return value in Collections.unmodifiableList. – Adamski Jul 02 '09 at 13:44
  • @Christoffer thanks. I have added the `set` method and now I can even sort the array... – freedev Jul 28 '14 at 12:17
46

The smallest piece of code would be:

public List<Integer> myWork(int[] array) {
    return Arrays.asList(ArrayUtils.toObject(array));
}

where ArrayUtils comes from commons-lang :)

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101
  • 12
    Just note `ArrayUtils` it's a relative big library for an Android app – msysmilu Nov 24 '15 at 13:30
  • 1
    The opposite operation is described here: https://stackoverflow.com/a/960507/1333157 `ArrayUtils.toPrimitive(...)` is the key. – ZeroOne May 29 '19 at 10:25
37

In Java 8 with stream:

int[] ints = {1, 2, 3};
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));

or with Collectors

List<Integer> list =  Arrays.stream(ints).boxed().collect(Collectors.toList());
user2037659
  • 491
  • 4
  • 5
23

In Java 8 :

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
Neeraj
  • 2,376
  • 2
  • 24
  • 41
23

If you are using java 8, we can use the stream API to convert it into a list.

List<Integer> list = Arrays.stream(arr)     // IntStream 
                                .boxed()        // Stream<Integer>
                                .collect(Collectors.toList());

You can also use the IntStream to convert as well.

List<Integer> list = IntStream.of(arr) // return Intstream
                                    .boxed()        // Stream<Integer>
                                    .collect(Collectors.toList());

There are other external library like guava and apache commons also available convert it.

cheers.

Mukesh Kumar Gupta
  • 1,567
  • 20
  • 15
13

It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:

"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."

Adamski
  • 54,009
  • 15
  • 113
  • 152
10
int[] arr = { 1, 2, 3, 4, 5 };

List<Integer> list = Arrays.stream(arr)     // IntStream
                            .boxed()        // Stream<Integer>
                            .collect(Collectors.toList());

see this

hamidreza75
  • 567
  • 6
  • 15
8

give a try to this class:

class PrimitiveWrapper<T> extends AbstractList<T> {

    private final T[] data;

    private PrimitiveWrapper(T[] data) {
        this.data = data; // you can clone this array for preventing aliasing
    }

    public static <T> List<T> ofIntegers(int... data) {
        return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
    }

    public static <T> List<T> ofCharacters(char... data) {
        return new PrimitiveWrapper(toBoxedArray(Character.class, data));
    }

    public static <T> List<T> ofDoubles(double... data) {
        return new PrimitiveWrapper(toBoxedArray(Double.class, data));
    }  

    // ditto for byte, float, boolean, long

    private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
        final int length = Array.getLength(components);
        Object res = Array.newInstance(boxClass, length);

        for (int i = 0; i < length; i++) {
            Array.set(res, i, Array.get(components, i));
        }

        return (T[]) res;
    }

    @Override
    public T get(int index) {
        return data[index];
    }

    @Override
    public int size() {
        return data.length;
    }
}

testcase:

List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc
dfa
  • 114,442
  • 31
  • 189
  • 228
6

The best shot:

    /**
     * Integer modifiable fixed length list of an int array or many int's.
     *
     * @author Daniel De Leon.
     */
    public class IntegerListWrap extends AbstractList<Integer> {
    
        int[] data;
    
        public IntegerListWrap(int... data) {
            this.data = data;
        }
    
        @Override
        public Integer get(int index) {
            return data[index];
        }
    
        @Override
        public Integer set(int index, Integer element) {
            int r = data[index];
            data[index] = element;
            return r;
        }
    
        @Override
        public int size() {
            return data.length;
        }
    }
  • Support get and set.
  • No memory data duplication.
  • No wasting time in loops.

Examples:

int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
plswork04
  • 589
  • 6
  • 11
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
4

Here is another possibility, again with Java 8 Streams:

void intArrayToListOfIntegers(int[] arr, List<Integer> list) {
    IntStream.range(0, arr.length).forEach(i -> list.add(arr[i]));
}
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
3

What about this:

int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);
Pang
  • 9,564
  • 146
  • 81
  • 122
humblefoolish
  • 409
  • 3
  • 15
2

If you're open to using a third party library, this will work in Eclipse Collections:

int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);

Note: I am a committer for Eclipse Collections.

Eric
  • 6,563
  • 5
  • 42
  • 66
Donald Raab
  • 6,458
  • 2
  • 36
  • 44
2
   /* Integer[] to List<Integer> */



        Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
        List<Integer> arrList = new ArrayList<>();
        arrList.addAll(Arrays.asList(intArr));
        System.out.println(arrList);


/* Integer[] to Collection<Integer> */


    Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
    Collection<Integer> c = Arrays.asList(intArr);
Uddhav P. Gautam
  • 7,362
  • 3
  • 47
  • 64
2

Here is a solution:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Amitabha Roy
  • 769
  • 5
  • 8
1

Here is a generic way to convert array to ArrayList

<T> ArrayList<T> toArrayList(Object o, Class<T> type){
    ArrayList<T> objects = new ArrayList<>();
    for (int i = 0; i < Array.getLength(o); i++) {
        //noinspection unchecked
        objects.add((T) Array.get(o, i));
    }
    return objects;
}

Usage

ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
1

You could use IntStream of and boxed it to Integer after that sorted using reverseOrder comparator.

List<Integer> listItems = IntStream.of(arrayItems)
                .boxed()
                .sorted(Collections.reverseOrder())
                .collect(Collectors.toList());

This approach has the advantage of being more flexible, as you can use different collectors to create different types of lists (e.g., an ArrayList, a LinkedList, etc.).

Levik
  • 111
  • 1
  • 6
0
Arrays.stream(ints).forEach(list::add);
prashant.kr.mod
  • 1,178
  • 13
  • 28