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

21

583

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.

Tamer answered 2/7, 2009 at 11:47 Comment(3)
We can make use of IntStream.Of(array).collect(Collectors.toList)Masturbate
@SarojKumarSahoo There is no one-argument collect in IntStream.Miletus
There is no build-in way to do it. You must do it manually, declare an ArrayList and add each value in the int Array to ArrayList. What a miss!Decorum
C
351

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);
}
Citral answered 2/7, 2009 at 11:52 Comment(14)
It is best to initialise the list with the size of the arrayHalmstad
@David Rabinowitz - Not sure what to say to that :)Citral
If you insist to use the ArrayList implementation, why not just use the overloaded constructor to do: new ArrayList(myArray) ?Exemplificative
I dont think there is such a constructorCitral
for (int i : ints) intList.add(i);Strikebreaker
@Citral - David means that this is better: new ArrayList<Integer>(ints.length);Strikebreaker
@willcodejavaforfood: declaring the size of the ArrayList when it is being constructed will prevent it having to internally resize after a certain amount is added. Not sure if the benefit is small, but there's definitely a benefit.Multiplicity
@StephenDenne That is not possible since ints may be any array like {3, 40, 50}. In your case, there will be ArrayIndexOutOfBoundsException.Rochester
@Danny: Don't edit the meaning of another person's answer for no good reason. This one was old and accepted, it would have been better to leave a comment.Stationer
@Rochester not sure why you think there would be an ArrayIndexOutOfBoundsException in Stephen Denne's for-loop.Hautrhin
The array list class empty constructor creates a list with size of ten in this case. The backend of the class is a Object[] with the size of ten elements. :)Polymorphous
new ArrayList<Integer>() {{ for (int i : ints) add(i); }}Hookah
@saka1029 For everyone thinking of using your solution, be aware that double brace initialisation comes with significant consequences. Use it wisely.Bergen
list.add(new int[]{1,2,3}); To create the list directly from the int arrayHoop
T
577

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();
Tareyn answered 8/5, 2014 at 16:59 Comment(10)
Equivalent to: Arrays.stream(ints).boxed().collect(Collectors.toList());Luck
@Luck You're right and IntStream.of just calls Arrays.stream so I've improved the answer following your suggestionTareyn
For some reason this doesn't seem to be returning the expected result type on Android Studio(works on eclipse) It says, expected List<Integer> found List<Object>.Scalise
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 runtimeTeets
@chitreshsirohi that is because lambda functions used inside streams result in Java to make some anonymous classes.Selfseeker
This solution is little complex to me. ------- I use bellow solution ----------------------- int[] ints = {1, 2, 3}; List<Integer> intList = new ArrayList<Integer>(ints.length); for (int i : ints) { intList.add(i); } If we talks about complexity, then which one is batter?Hehre
IntStream.of(array).boxed().collect(Collectors.toList());Coercion
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))Fauces
I am getting code sonar issue i.e "Closeable Not Stored(Java)". Is there any way we can avoid this sonar issue?Bilk
The only issue here is that the resulting list is immutable as toList() is really this call return (List<T>) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray()))); This means you can only read this list and won't be able to change it in anyway.Gobelin
C
351

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);
}
Citral answered 2/7, 2009 at 11:52 Comment(14)
It is best to initialise the list with the size of the arrayHalmstad
@David Rabinowitz - Not sure what to say to that :)Citral
If you insist to use the ArrayList implementation, why not just use the overloaded constructor to do: new ArrayList(myArray) ?Exemplificative
I dont think there is such a constructorCitral
for (int i : ints) intList.add(i);Strikebreaker
@Citral - David means that this is better: new ArrayList<Integer>(ints.length);Strikebreaker
@willcodejavaforfood: declaring the size of the ArrayList when it is being constructed will prevent it having to internally resize after a certain amount is added. Not sure if the benefit is small, but there's definitely a benefit.Multiplicity
@StephenDenne That is not possible since ints may be any array like {3, 40, 50}. In your case, there will be ArrayIndexOutOfBoundsException.Rochester
@Danny: Don't edit the meaning of another person's answer for no good reason. This one was old and accepted, it would have been better to leave a comment.Stationer
@Rochester not sure why you think there would be an ArrayIndexOutOfBoundsException in Stephen Denne's for-loop.Hautrhin
The array list class empty constructor creates a list with size of ten in this case. The backend of the class is a Object[] with the size of ten elements. :)Polymorphous
new ArrayList<Integer>() {{ for (int i : ints) add(i); }}Hookah
@saka1029 For everyone thinking of using your solution, be aware that double brace initialisation comes with significant consequences. Use it wisely.Bergen
list.add(new int[]{1,2,3}); To create the list directly from the int arrayHoop
R
194

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

List<Integer> Ints.asList(int...)
Riggall answered 8/6, 2010 at 19:53 Comment(4)
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."Seigel
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.Equilibrium
Beware of the method reference count on Android when adding libraries. Good find though.Upstanding
In Android I had to add implementation 'com.google.firebase:firebase-crashlytics-buildtools:2.9.0' to build.gradle for this to work.Rader
D
117

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);
Dogma answered 2/7, 2009 at 12:11 Comment(3)
Do note, that that list is immutableBeriosova
Arrays.asList(arr) in the above comment will generate a list of type List<int[]> which is incompatible with List<Integer>. If one were to try to assign the output to a variable like so ``` List<Integer> 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<Integer> l = Arrays.asList(a); | ^--------------^Nat
this is wrong! it generates List<int[]>Hagar
S
56

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; }
    };
}
Steamtight answered 2/7, 2009 at 12:26 Comment(4)
+1 this is shorter than mine but mine works for all primitives typesSufficiency
While quicker and using less memory than creating an ArrayList, the trade off is List.add() and List.remove() don't work.Strikebreaker
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.Quillen
@Steamtight thanks. I have added the set method and now I can even sort the array...Cerf
A
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 :)

Adduct answered 9/4, 2010 at 12:1 Comment(2)
Just note ArrayUtils it's a relative big library for an Android appCountermove
The opposite operation is described here: https://mcmap.net/q/41530/-how-can-i-convert-list-lt-integer-gt-to-int-in-java-duplicate ArrayUtils.toPrimitive(...) is the key.Nodose
B
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());
Bandsman answered 28/4, 2014 at 12:3 Comment(1)
Why not simply use a collector?Ingeborgingelbert
T
24

In Java 8 :

int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
Tillietillinger answered 2/11, 2017 at 8:50 Comment(0)
T
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.

Twocycle answered 18/7, 2019 at 19:45 Comment(0)
Q
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."

Quillen answered 2/7, 2009 at 12:8 Comment(0)
L
10
int[] arr = { 1, 2, 3, 4, 5 };

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

see this

Lanna answered 15/6, 2020 at 8:16 Comment(0)
S
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
Sufficiency answered 2/7, 2009 at 12:24 Comment(0)
S
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);
Schoonover answered 10/6, 2012 at 7:28 Comment(1)
I like it the most. But I'd still use guava to have straight-forward solution :)Injection
C
4

What about this:

int[] a = {1,2,3};
Integer[] b = ArrayUtils.toObject(a);
List<Integer> c = Arrays.asList(b);
Campfire answered 23/3, 2018 at 17:31 Comment(0)
M
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]));
}
Mathes answered 25/11, 2018 at 4:18 Comment(0)
A
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.

Ataghan answered 29/1, 2017 at 4:7 Comment(0)
T
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);
Treasatreason answered 16/8, 2017 at 18:23 Comment(0)
S
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]
Serow answered 20/4, 2018 at 9:40 Comment(0)
E
2

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

Endocarp answered 29/12, 2022 at 13:13 Comment(0)
M
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);
Monosaccharide answered 30/1, 2016 at 7:15 Comment(0)
S
0
Arrays.stream(ints).forEach(list::add);
Stonemason answered 1/8, 2020 at 21:46 Comment(1)
@TomerShetah the statement is self explanatory. I expect reader to have a minimal understanding of Java Stream API.Stonemason

© 2022 - 2024 — McMap. All rights reserved.