1269

How do I convert an array to a list in Java?

I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.

For example:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(numbers)
  • on 1.4.2 returns a list containing the elements 1, 2, 3
  • on 1.5.0+ returns a list containing the array 'numbers'

In many cases it should be easy to detect, but sometimes it can slip unnoticed:

Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);
Michael
  • 41,989
  • 11
  • 82
  • 128
Alexandru
  • 25,070
  • 18
  • 69
  • 78
  • 25
    I think your example is broken: `Arrays.asList(new int[] { 1, 2, 3 })`; definitely didn't compile in Java 1.4.2, because an `int[]` is **not** a `Object[]`. – Joachim Sauer Apr 09 '10 at 12:28
  • 1
    Oh, you may be right. I didn't have Java 1.4.2 compiler around to test my example before posting. Now, after your comment and Joe's answer, everything makes much more sense. – Alexandru Apr 09 '10 at 12:34
  • 1
    I thought Autoboxing would have covered conversion from primitive to wrapper Integer class. You can make the cast yourself first and then the above code for `Arrays.asList` should work. – Horse Voice Sep 03 '13 at 17:54
  • 2
    Java 8's Stream.boxed() will take care of the autoboxing and can be used for this. See my answer [below](http://stackoverflow.com/a/30281879/752918). – Ibrahim Arief May 18 '15 at 12:01

25 Answers25

1699

In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.

You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.

Integer[] numbers = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(numbers);

See this code run live at IdeOne.com.

Michael
  • 41,989
  • 11
  • 82
  • 128
Joe Daley
  • 45,356
  • 15
  • 65
  • 64
  • 127
    Or even simpler: Arrays.asList(1, 2, 3); – Kong Aug 24 '13 at 02:18
  • 66
    How does it know not to create a `List`? – Thomas Ahle Apr 06 '14 at 22:07
  • 8
    @ThomasAhle It does not create a List it creates a List object. And if you want to be type safe you write: Arrays.asList(spam); – user1712376 May 23 '14 at 20:24
  • 1
    @user1712376 I just mean, it's odd. If I want to create a list of one `Long x` I would do `Arrays.asList(x)`. If I want to create a list of one `Long[] x2` I would do `Arrays.asList(x2)`, but now I'm not sure what I would get out... – Thomas Ahle May 23 '14 at 20:47
  • 2
    @ThomasAhle you could pass in Arrays.asList 0 or more elements, in comma separated format or array format whichever you desire. And the result will always be the same - a list of the elements you specified. And this is because of the method signature : public static List asList(T... a). Here you can read more about varargs http://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html#varargs – user1712376 May 23 '14 at 22:42
  • 9
    @ThomasAhle That is a good question. A guess it's just a rule in the java compiler. For exemple the following code returns a List `Integer[] integerArray1 = { 1 }; Integer[] integerArray2 = { 2 }; List integerArrays = Arrays.asList(integerArray1, integerArray2); ` – Simon Nov 03 '14 at 19:19
  • Yes, it seems like the have a special rule for detecting when single arrays are passed. I wonder if `Arrays.asList(spam);` would give a compile error? – Thomas Ahle Nov 04 '14 at 16:35
  • For me in failed if I used the primitive type array. I.e. int[]. The result was List – Lingviston Aug 25 '16 at 13:21
  • I have "double[] observations", and doing "Arrays.asList(observations) " returns "List" which obviously is not what I needed! – pedram bashiri Apr 10 '17 at 19:27
  • 2
    @pedrambashiri It doesn't work for primitive arrays, like `int[]`, `long[]`, `double[]`, just for `Integer[]`, `Long[]`, `Double[]` ... – deFreitas Sep 24 '17 at 02:21
  • 1
    @deFreitas exactly, and the question was for a primitive array int[] – pedram bashiri Jan 03 '18 at 22:36
  • .asList() method on Arrays returns an ArrayList. The method accepts variable arguments of primitive type. As only primitive data types can be used as generic for Collections, this explains the reason for compile time failure. – NiNa Sep 13 '18 at 08:41
  • 2
    Remember that, Arrays.asList() returns an Arrays$ArrayList which is fixed-size list and keep reference to the original array. It provides an api to work with actual array via List's methods. – tienthanhakay Jan 02 '19 at 10:55
  • 1
    There's no special rule. It doesn't create a `List` because the input is an `Integer[]`, not a `Integer[][]`. You passed a `Integer[]` so it returns a `List`. I think it's helpful to remember that java varargs is just syntactic sugar on top of object arrays. `T... a` in `asList` is just a `T[]`, which is converted to a `List`. If you had passed two `Integer[]` (separated by commas) or a `Integer[][]` it would return a `List`. `Arrays.asList(new Integer[]{1,2}, new Integer[]{3,4});` is equivalent to `Arrays.asList(new Integer[][]{{1,2}, {3,4}});` – theferrit32 Aug 03 '19 at 00:23
  • 2
    What happens when you send it a primitive array, is that it interprets that primitive array as the first vararg. This happens because `asList` requires objects because it and `List` use generic typing which requires objects, not primitives. Since an `int` is not an object, but an `int[]` is an object, it interprets it differently than if you sent an `Integer[]` which is an object array containing `Integer` objects. So in the second case it treats the `Integers` within the array as the vararg terms instead of the `Integer[]` as a vararg term itself. – theferrit32 Aug 03 '19 at 00:26
  • 2
    @theferrit32 you can create a `List list = Arrays.asList(spam);` The logic has been specified in JLS §15.12.2. The reason is, as you said, that varargs are syntactic sugar for an array argument and hence, have to stay backwards compatible to code passing in a matching array. – Holger Aug 19 '20 at 07:54
  • 1
    This doesnt answer the question. Can you please update your answer on how to convert int[] to Integer[]? Op has a primitive int[] not wrapper Integer[]. – theprogrammer Feb 07 '21 at 02:21
  • Beware! The array is still behind the list interface, which means you cant remove something as the array has a fixed size! – Pwnstar Jun 30 '21 at 09:42
260

In Java 8, you can use streams:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.stream(numbers)
      .boxed()
      .collect(Collectors.toList());
Michael
  • 41,989
  • 11
  • 82
  • 128
Ibrahim Arief
  • 8,742
  • 6
  • 34
  • 54
  • 1
    This is nice, but it won't work for `boolean[]`. I guess that's because it's just as easy to make a `Boolean[]`. That's probably a better solution. Anyway, it's an interesting quirk. – GlenPeterson Feb 21 '20 at 18:58
  • 4
    simplified in Java 16 as Arrays.stream(spam).boxed().toList(); – Gonen I Nov 23 '21 at 11:26
191

We cannot have List<int> as int is a primitive type so we can only have List<Integer>.

Java 16

Java 16 introduces a new method on Stream API called toList(). This handy method returns an unmodifiable List containing the stream elements. So, trying to add a new element to the list will simply lead to UnsupportedOperationException.

int[] ints = new int[] {1,2,3,4,5};
Arrays.stream(ints).boxed().toList();

Java 8 (int array)

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

Java 8 and below (Integer array)

Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 =  Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only

Need ArrayList and not List?

In case we want a specific implementation of List e.g. ArrayList then we can use toCollection as:

ArrayList<Integer> list24 = Arrays.stream(integers)
                          .collect(Collectors.toCollection(ArrayList::new));

Why list21 cannot be structurally modified?

When we use Arrays.asList the size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationException will be thrown. So we should go with list22 when we want to modify the list. If we have Java8 then we can also go with list23.

To be clear list21 can be modified in sense that we can call list21.set(index,element) but this list may not be structurally modified i.e. cannot add or remove elements from the list. You can also check this answer of mine for more explanation.


If we want an immutable list then we can wrap it as:

List<Integer> list22 = Collections.unmodifiableList(Arrays.asList(integers));

Another point to note is that the method Collections.unmodifiableList returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.

We can have a truly immutable list in Java 9 and 10.

Truly Immutable list

Java 9:

String[] objects = {"Apple", "Ball", "Cat"};
List<String> objectList = List.of(objects);

Java 10 (Truly Immutable list):

We can use List.of introduced in Java 9. Also other ways:

  1. List.copyOf(Arrays.asList(integers))
  2. Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
TylerH
  • 20,799
  • 66
  • 75
  • 101
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • @BasilBourque I meant cannot modify the list's structure by addition/deletion but can change the elements. – akhil_mittal Feb 03 '19 at 03:28
  • Indeed, I tried some code and confirmed that calling `List::add` & `List::remove` fails with a list returned by `Arrays.asList`. The JavaDoc for that method is poorly written and unclear on this point. On my third reading, I suppose the phrase “fixed-size” there was meant to say one cannot add or remove elements. – Basil Bourque Feb 03 '19 at 05:38
  • comprehensive answer and should be accepted. – Mubasher Apr 10 '23 at 08:49
151

Speaking about conversion way, it depends on why do you need your List. If you need it just to read data. OK, here you go:

Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);

But then if you do something like this:

list.add(1);

you get java.lang.UnsupportedOperationException. So for some cases you even need this:

Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));

First approach actually does not convert array but 'represents' it like a List. But array is under the hood with all its properties like fixed number of elements. Please note you need to specify type when constructing ArrayList.

Roman Nikitchenko
  • 12,800
  • 7
  • 74
  • 110
  • 1
    "immutability" confused me for a moment. You can obviously change the array's values. You cannot change its size, however. – Tim Pohlmann Oct 18 '17 at 07:25
133

The problem is that varargs got introduced in Java 5 and unfortunately, Arrays.asList() got overloaded with a vararg version too. So Arrays.asList(numbers) is understood by the Java 5 compiler as a vararg parameter of int arrays.

This problem is explained in more details in Effective Java 2nd Ed., Chapter 7, Item 42.

Michael
  • 41,989
  • 11
  • 82
  • 128
Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • 4
    I understand what happened, but not why it is not documented. I am looking for an alternative solution without reimplementing the wheel. – Alexandru Apr 09 '10 at 12:28
16

I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.

In the end, I had to do a "manual" conversion:

    List<ListItem> items = new ArrayList<ListItem>();
    for (ListItem item: itemsArray) {
        items.add(item);
    }

I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.

Community
  • 1
  • 1
Steve Gelman
  • 874
  • 9
  • 16
  • 12
    `new ArrayList(Arrays.asList(itemsArray))` would to the same – Marco13 Aug 31 '14 at 17:38
  • 1
    @BradyZhu: Granted the answer above does not solve my problem with the fixed size array, but you are basically saying RTFM here, which is always bad form. Please expound on what is wrong with the answer or don't bother to comment. – Steve Gelman Feb 25 '15 at 15:05
  • 2
    Inspection tools may show a warning here, and you've named the reason. There is no need to copy the elements manually, use `Collections.addAll(items, itemsArray)` instead. – Darek Kay Apr 24 '15 at 13:34
  • Just hit this exception. I am afraid Marco13's answer should be the correct answer. I may need to go though whole year code to fix all "asList" exception. –  Jul 06 '16 at 09:35
11

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);
Vitaliy Sokolov
  • 127
  • 1
  • 2
9

Another workaround if you use Apache commons-lang:

int[] numbers = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(numbers));

Where ArrayUtils.toObject converts int[] to Integer[]

Michael
  • 41,989
  • 11
  • 82
  • 128
alaster
  • 3,821
  • 3
  • 24
  • 32
9

Using Arrays

This is the simplest way to convert an array to List. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException will be thrown.

Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);

// WARNING:
list2.add(1);     // Unsupported operation!
list2.remove(1);  // Unsupported operation!

Using ArrayList or Other List Implementations

You can use a for loop to add all the elements of the array into a List implementation, e.g. ArrayList:

List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
  list.add(i);
}

Using Stream API in Java 8

You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList behind the screen, but you can also impose your preferred implementation.

List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));

See also:

Mincong Huang
  • 5,284
  • 8
  • 39
  • 62
9

In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of:

List<String> immutableList = List.of("one","two","three");

(shamelessly copied from here )

Alan Bateman
  • 5,283
  • 1
  • 20
  • 25
Pierluigi Vernetto
  • 1,954
  • 1
  • 25
  • 27
  • FYI, to learn some of the technical details behind this, see [*JEP 269: Convenience Factory Methods for Collections*](http://openjdk.java.net/jeps/269) and [a talk by Stuart Marks](https://www.youtube.com/watch?v=OJrIMv4dAek), the principal author. – Basil Bourque Jul 29 '18 at 07:12
7

One-liner:

List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
Bhushan
  • 18,329
  • 31
  • 104
  • 137
7

If you are targeting Java 8 (or later), you can try this:

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

NOTE:

Pay attention to the Collectors.<Integer>toList(), this generic method helps you to avoid the error "Type mismatch: cannot convert from List<Object> to List<Integer>".

Radiodef
  • 37,180
  • 14
  • 90
  • 125
nybon
  • 8,894
  • 9
  • 59
  • 67
6

you have to cast in to array

Arrays.asList((Object[]) array)
4

I've had the same problem and wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:

public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
    ArrayList<T> list = new ArrayList<T>();
    for(T elmt : array) list.add(elmt);
    return list;
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
4
  1. Using Guava:

    Integer[] array = { 1, 2, 3};
    List<Integer> list = Lists.newArrayList(sourceArray);
    
  2. Using Apache Commons Collections:

    Integer[] array = { 1, 2, 3};
    List<Integer> list = new ArrayList<>(6);
    CollectionUtils.addAll(list, array);
    
3

Given Array:

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

Converting integer array to Integer List

One way: boxed() -> returns the IntStream

    List<Integer> givenIntArray1 = Arrays.stream(givenArray)
                                  .boxed()
                                  .collect(Collectors.toList());

Second Way: map each element of the stream to Integer and then collect

NOTE: Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i

    List<Integer> givenIntArray2 = Arrays.stream(givenArray)
                                         .mapToObj(i->i)
                                         .collect(Collectors.toList());

Converting One array Type to Another Type Example:

List<Character> givenIntArray2 = Arrays.stream(givenArray)
                                             .mapToObj(i->(char)i)
                                             .collect(Collectors.toList());
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
1

use two line of code to convert array to list if you use it in integer value you must use autoboxing type for primitive data type

  Integer [] arr={1,2};
  List<Integer> listInt=Arrays.asList(arr);
yousef
  • 1,345
  • 1
  • 12
  • 20
1

So it depends on which Java version you are trying-

Java 7

 Arrays.asList(1, 2, 3);

OR

       final String arr[] = new String[] { "G", "E", "E", "K" };
       final List<String> initialList = new ArrayList<String>() {{
           add("C");
           add("O");
           add("D");
           add("I");
           add("N");
       }};

       // Elements of the array are appended at the end
       Collections.addAll(initialList, arr);

OR

Integer[] arr = new Integer[] { 1, 2, 3 };
Arrays.asList(arr);

In Java 8

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

Reference - http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/

Hitesh Garg
  • 1,211
  • 1
  • 10
  • 21
1

Use this to convert an Array arr to List. Arrays.stream(arr).collect(Collectors.toList());

An example of defining a generic method to convert an array to a list:

public <T> List<T> fromArrayToList(T[] a) {   
    return Arrays.stream(a).collect(Collectors.toList());
}
1

As of Java 8, the following should do

int[] temp = {1, 2, 3, 4, 5};
List<Integer> tempList = Arrays.stream(temp).boxed().collect(Collectors.toList());
ivenpoker
  • 69
  • 7
0

Can you improve this answer please as this is what I use but im not 100% clear. It works fine but intelliJ added new WeatherStation[0]. Why the 0 ?

    public WeatherStation[] removeElementAtIndex(WeatherStation[] array, int index)
    {
        List<WeatherStation> list = new ArrayList<WeatherStation>(Arrays.asList(array));
        list.remove(index);
        return list.toArray(new WeatherStation[0]);
    }
DevilCode
  • 1,054
  • 3
  • 35
  • 61
  • Why should **we** improve **your** question? Either you know the answer, or you don´t. You should of course provide an answer that really helps others, not one that confuses more than it helps. – MakePeaceGreatAgain Jan 19 '20 at 12:57
0

If you are trying to optimize for memory, etc., (and don't want to pull in external libraries) it's simpler than you think to implement your own immutable "array view list" – you just need to extend java.util.AbstractList.

class IntArrayViewList extends AbstractList<Integer> {
    int[] backingArray;
    int size;

    IntArrayViewList(int[] backingArray, int size) {
        this.backingArray = backingArray;
        this.size = size;
    }

    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;

            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return get(i++);
            }
        };
    }

    public int size() {
        return size;
    }

    public Integer get(int i) {
        return backingArray[i];
    }
}
ATOMP
  • 1,311
  • 10
  • 29
0

int is a primitive. Primitives can’t accept null and have default value. Hence, to accept null you need to use wrapper class Integer.

Option 1:

int[] nos = { 1, 2, 3, 4, 5 };
Integer[] nosWrapped = Arrays.stream(nos).boxed()   
                                        .toArray(Integer[]::new);
nosWrapped[5] = null // can store null

Option 2: You can use any data structure that uses the wrapper class Integer

int[] nos = { 1, 2, 3, 4, 5 };
List<Integer> = Arrays.asList(nos)
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
0

I started looking at this by trying to reduce the amount of code preparing the input of some test cases. I see a lot of effort around trying to include advanced and new features along with Arrays.asList(), but below the code chosen due simplicity:

    //Integer input[]
    List<Integer> numbers = Arrays.asList(new Integer[]{1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4});
    
    //String input[]
    List<String> names = Arrays.asList(new String[]{"Jhon", "Lucas", "Daniel", "Jim", "Sam"});
    
    //String input[]
    List<Character> letters = Arrays.asList(new Character[]{'A', 'B', 'K', 'J', 'F'});
    

Please notice that Anonymous array example will work just with Arrays of Non Primitive Types as the API uses Generics, that's the reason you can see several 2 line examples around, more info here: Why don't Java Generics support primitive types?

For newer JDKs there is another simpler option, the below examples are equivalent to the ones show above:

    //Integer
    List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 4, 3, 2, 1, 3, 4);
    
    //String
    List<String> names = Arrays.asList("Jhon", "Lucas", "Daniel", "Jim", "Sam"); 
    
    //Character
    List<Character> letters = Arrays.asList('A', 'B', 'K', 'J', 'F');
Enrique Palacio
  • 1,521
  • 13
  • 8
0

"... How do I convert an array to a list in Java? ..."

There are several ways to accomplish this task.
And, depending on the data-type, some solutions may require more code.

The most simple approach is to traverse the array, and append each value to a List.

int[] values = { 1, 2, 3 };
List<Integer> list = new ArrayList<>();
for (int value : values) list.add(value);

Although, if you're not using a primitive data-type, you can utilize the List#of method, and get rid of the loop.
To create a mutable List, I supplied the value as a new ArrayList parameter.

String[] strings = { "a", "b", "c" };
List<String> list = new ArrayList<>(List.of(strings));
Integer[] numbers = { 1, 2, 3 };
List<Integer> list = new ArrayList<>(List.of(numbers));

Additionally, you can stream the array, to derive a List object.

For a primitive data-type array, it will take slightly more effort.
The Collections Framework was built specifically for objects, and not primitive data-types.
It's recommended to use the wrapper-classes, Integer, Float, etc., for any resourced array objects.

You can stream the array using the Arrays#stream method.
This will return an IntStream, which you can then call the boxed method on, which returns a stream of wrapped, or "boxed" values.
Finally, use the Stream#toList method to return the boxed stream as a List.

Again, to obtain a mutable List, I supplied the value as a new ArrayList parameter.

int[] numbers = { 1, 2, 3 };
List<Integer> list = new ArrayList<>(Arrays.stream(numbers).boxed().toList());

On a final note, if you're simply looking to add an array of values to a List, just use the List#of method.
Just remember this produces an immutable List.

Immutable:

List<Integer> list = List.of(1, 2, 3);

Mutable:

List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
Reilas
  • 3,297
  • 2
  • 4
  • 17