By pupeno


2009-07-02 11:47:36 8 Comments

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.

18 comments

@Solomon Ucko 2019-01-03 03:44:51

I wonder if something along the lines of Arrays.asList(...array) would work...

@Koray Tugay 2018-11-25 04:18:47

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

@mikeyreilly 2014-05-08 16:59:46

Streams

In Java 8 you can do this

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

@njfrost 2016-07-01 17:12:17

Equivalent to: Arrays.stream(ints).boxed().collect(Collectors.toList());

@mikeyreilly 2017-10-04 08:00:26

@njfrost You're right and IntStream.of just calls Arrays.stream so I've improved the answer following your suggestion

@Eugenio Lopez 2018-08-07 19:13:53

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

@Amitabha Roy 2018-04-20 09:40:00

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]

@humblefoolish 2018-03-23 17:31:10

What about this:

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

@willcodejavaforfood 2009-07-02 11:52:05

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>();
for (int i : ints)
{
    intList.add(i);
}

@David Rabinowitz 2009-07-02 11:54:28

It is best to initialise the list with the size of the array

@willcodejavaforfood 2009-07-02 11:55:41

@David Rabinowitz - Not sure what to say to that :)

@Jørn Schou-Rode 2009-07-02 11:56:09

If you insist to use the ArrayList implementation, why not just use the overloaded constructor to do: new ArrayList(myArray) ?

@willcodejavaforfood 2009-07-02 12:01:18

I dont think there is such a constructor

@Stephen Denne 2009-07-02 12:19:29

for (int i : ints) intList.add(i);

@Stephen Denne 2009-07-02 12:25:17

@willcodejavaforfood - David means that this is better: new ArrayList<Integer>(ints.length);

@Grundlefleck 2010-01-24 20:22:46

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

@Daemonthread 2012-01-24 09:19:38

@StephenDenne That is not possible since ints may be any array like {3, 40, 50}. In your case, there will be ArrayIndexOutOfBoundsException.

@Junuxx 2012-10-04 11:48:42

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

@bcorso 2014-06-06 18:22:57

@Daemonthread not sure why you think there would be an ArrayIndexOutOfBoundsException in Stephen Denne's for-loop.

@br1337 2014-10-31 11:36:38

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

@saka1029 2015-07-02 01:55:04

new ArrayList<Integer>() {{ for (int i : ints) add(i); }}

@klaar 2015-12-16 14:43:30

@saka1029 For everyone thinking of using your solution, be aware that double brace initialisation comes with significant consequences. Use it wisely.

@Neeraj 2017-11-02 08:50:52

In Java 8 :

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

@Uddhav Gautam 2017-08-16 18:23:26

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

@Donald Raab 2017-01-29 04:07:22

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.

@Daniel De León 2012-06-10 07:28:48

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

@dantuch 2012-08-19 23:27:33

I like it the most. But I'd still use guava to have straight-forward solution :)

@Kannan Ekanath 2010-04-09 12:01:32

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

@msysmilu 2015-11-24 13:30:45

Just note ArrayUtils it's a relative big library for an Android app

@ZeroOne 2019-05-29 10:25:45

The opposite operation is described here: stackoverflow.com/a/960507/1333157 ArrayUtils.toPrimitive(...) is the key.

@Christoffer 2009-07-02 12:26:59

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

@dfa 2009-07-02 12:31:50

+1 this is shorter than mine but mine works for all primitives types

@Stephen Denne 2009-07-02 13:03:00

While quicker and using less memory than creating an ArrayList, the trade off is List.add() and List.remove() don't work.

@Adamski 2009-07-02 13:44:38

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.

@Jay Thakkar 2013-12-19 11:23:07

Thanks Bro it works ..Adi

@freedev 2014-07-28 12:17:15

@Christoffer thanks. I have added the set method and now I can even sort the array...

@Ilya Gazman 2016-01-30 07:15:57

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

@user2037659 2014-04-28 12:03:27

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

@assylias 2014-05-18 12:23:41

Why not simply use a collector?

@louisgab 2010-06-08 19:53:47

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

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

@josketres 2014-04-22 12:22:24

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

@craastad 2014-08-07 14:28:42

Thank you thank you thank you! Also works for Longs.asList(long...).

@pburka 2015-04-22 15:45:29

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.

@milosmns 2016-10-03 13:39:13

Beware of the method reference count on Android when adding libraries. Good find though.

@dfa 2009-07-02 12:24:36

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

@Leonel 2009-07-02 12:11:56

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

@Daniel De León 2012-06-10 07:41:38

Nice information!

@phoenixSid 2018-07-14 08:34:02

Good explanation. +1

@Danielson 2018-09-21 16:22:03

Do note, that that list is immutable

@Adamski 2009-07-02 12:08:39

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

Related Questions

Sponsored Content

80 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5764219 View
  • 7192 Score
  • 79 Answer
  • Tags:   javascript arrays

39 Answered Questions

[SOLVED] How do I efficiently iterate over each entry in a Java Map?

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3802522 View
  • 3232 Score
  • 64 Answer
  • Tags:   java random integer

31 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

45 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

44 Answered Questions

[SOLVED] How to check if an object is an array?

23 Answered Questions

16 Answered Questions

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

Sponsored Content