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

JavaArraysCollectionsBoxingAutoboxing

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

List<Integer> Ints.asList(int...)

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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 :)

Solution 7 - Java

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

Solution 8 - Java

In Java 8 :

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());

Solution 9 - Java

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.

Solution 10 - Java

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."

Solution 11 - Java

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

Solution 12 - Java

The best shot:

**
 * Integer modifiable fix 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);

Solution 13 - Java

int[] arr = { 1, 2, 3, 4, 5 };

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

see this

Solution 14 - Java

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

Solution 15 - Java

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.

Solution 16 - Java

   /* 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);

Solution 17 - Java

What about this:

int[] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);

Solution 18 - Java

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]

Solution 19 - Java

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

Solution 20 - Java

Arrays.stream(ints).forEach(list::add);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpupenoView Question on Stackoverflow
Solution 1 - JavamikeyreillyView Answer on Stackoverflow
Solution 2 - JavawillcodejavaforfoodView Answer on Stackoverflow
Solution 3 - JavalouisgabView Answer on Stackoverflow
Solution 4 - JavaLeonelView Answer on Stackoverflow
Solution 5 - JavaChristofferView Answer on Stackoverflow
Solution 6 - JavaKannan EkanathView Answer on Stackoverflow
Solution 7 - Javauser2037659View Answer on Stackoverflow
Solution 8 - JavaNeerajView Answer on Stackoverflow
Solution 9 - JavaMukesh Kumar GuptaView Answer on Stackoverflow
Solution 10 - JavaAdamskiView Answer on Stackoverflow
Solution 11 - JavadfaView Answer on Stackoverflow
Solution 12 - JavaDaniel De LeónView Answer on Stackoverflow
Solution 13 - Javahamidreza75View Answer on Stackoverflow
Solution 14 - JavaKoray TugayView Answer on Stackoverflow
Solution 15 - JavaDonald RaabView Answer on Stackoverflow
Solution 16 - JavaUddhav P. GautamView Answer on Stackoverflow
Solution 17 - JavahumblefoolishView Answer on Stackoverflow
Solution 18 - JavaAmitabha RoyView Answer on Stackoverflow
Solution 19 - JavaIlya GazmanView Answer on Stackoverflow
Solution 20 - Javaprashant.kr.modView Answer on Stackoverflow