By Alexandru


2010-04-09 12:20:20 8 Comments

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[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)
  • on 1.4.2 returns a list containing the elements 1, 2, 3
  • on 1.5.0+ returns a list containing the array spam

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

Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);

19 comments

@i_am_zero 2015-12-23 05:07:03

It seems little late but here are my two cents. We cannot have List<int> as int is a primitive type so we can only have List<Integer>.

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


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

List<Integer> list 22 = 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) in two ways:

  1. List.copyOf(Arrays.asList(integers))
  2. Arrays.stream(integers).collect(Collectors.toUnmodifiableList());

Also check this answer of mine for more.

@i_am_zero 2019-02-03 03:28:18

@BasilBourque I meant cannot modify the list's structure by addition/deletion but can change the elements.

@Basil Bourque 2019-02-03 05:38:45

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.

@DevilCode 2019-11-13 22:57:06

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

@Arpan Saini 2019-09-07 19:16:21

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

@Joe Daley 2010-04-09 12:27:23

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[] spam = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(spam);

See this code run live at IdeOne.com.

@Kong 2013-08-24 02:18:17

Or even simpler: Arrays.asList(1, 2, 3);

@Thomas Ahle 2014-04-06 22:07:57

How does it know not to create a List<Integer[]>?

@djechlin 2014-04-24 17:51:47

Fails in Java 5+.

@user1712376 2014-05-23 20:24:27

@ThomasAhle It does not create a List<Integer[]> it creates a List<Integer> object. And if you want to be type safe you write: Arrays.<Integer>asList(spam);

@Thomas Ahle 2014-05-23 20:47:50

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

@user1712376 2014-05-23 22:42:49

@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 <T> List<T> asList(T... a). Here you can read more about varargs docs.oracle.com/javase/tutorial/java/javaOO/…

@Simon 2014-11-03 19:19:32

@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[]> Integer[] integerArray1 = { 1 }; Integer[] integerArray2 = { 2 }; List<Integer[]> integerArrays = Arrays.asList(integerArray1, integerArray2);

@Thomas Ahle 2014-11-04 16:35:46

Yes, it seems like the have a special rule for detecting when single arrays are passed. I wonder if Arrays.<Integer[]>asList(spam); would give a compile error?

@Lingviston 2016-08-25 13:21:58

For me in failed if I used the primitive type array. I.e. int[]. The result was List<Integer[]>

@pedram bashiri 2017-04-10 19:27:00

I have "double[] observations", and doing "Arrays.asList(observations) " returns "List<double[]>" which obviously is not what I needed!

@deFreitas 2017-09-24 02:21:29

@pedrambashiri It doesn't work for primitive arrays, like int[], long[], double[], just for Integer[], Long[], Double[] ...

@pedram bashiri 2018-01-03 22:36:21

@deFreitas exactly, and the question was for a primitive array int[]

@NiNa 2018-09-13 08:41:58

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

@tienthanhakay 2019-01-02 10:55:16

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.

@theferrit32 2019-08-03 00:23:33

There's no special rule. It doesn't create a List<Integer[]> because the input is an Integer[], not a Integer[][]. You passed a Integer[] so it returns a List<Integer>. 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<T>. If you had passed two Integer[] (separated by commas) or a Integer[][] it would return a List<Integer[]>. Arrays.asList(new Integer[]{1,2}, new Integer[]{3,4}); is equivalent to Arrays.asList(new Integer[][]{{1,2}, {3,4}});

@theferrit32 2019-08-03 00:26:58

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.

@nybon 2016-08-12 14:52:00

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

@Danail Tsvetanov 2018-04-02 13:03:33

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

@Pierluigi Vernetto 2017-11-28 23:22:50

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 )

@Basil Bourque 2018-07-29 07:12:53

FYI, to learn some of the technical details behind this, see JEP 269: Convenience Factory Methods for Collections and a talk by Stuart Marks, the principal author.

@Roman Nikitchenko 2014-09-27 16:22:07

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.

@Tim Pohlmann 2017-10-18 07:25:36

"immutability" confused me for a moment. You can obviously change the array's values. You cannot change its size, however.

@kleines filmröllchen 2017-09-05 15:19:05

If this helps: I've had the same problem and simply 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;
}

@Sᴀᴍ Onᴇᴌᴀ 2017-09-05 15:40:21

What if it doesn't help? Then what did you do?? ... jk :)

@Hitesh Garg 2017-07-28 06:21:57

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/

@yousef 2017-06-11 08:31:10

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};
  Arrays.asList(arr);

@Mincong Huang 2017-03-04 22:12:46

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:

@Péter Török 2010-04-09 12:26:26

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

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

@Alexandru 2010-04-09 12:28:44

I understand what happened, but not why it is not documented. I am looking for an alternative solution without reimplementing the wheel.

@Ibrahim Arief 2015-05-18 11:59:20

@UsmanIsmail As of Java 8, we can use streams for this conversion. See my answer below.

@Vitaliy Sokolov 2016-03-17 09:55:05

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

@Bhushan 2016-03-11 04:15:46

One-liner:

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

@alaster 2015-09-21 12:27:21

Another workaround if you use apache commons-lang:

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

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

@Ibrahim Arief 2015-05-16 23:49:16

In Java 8, you can use streams:

int[] spam = new int[] { 1, 2, 3 };
Arrays.stream(spam)
      .boxed()
      .collect(Collectors.toList());

@Steve Gelman 2014-08-31 17:26:24

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.

@Marco13 2014-08-31 17:38:31

new ArrayList<ListItem>(Arrays.asList(itemsArray)) would to the same

@Steve Gelman 2015-02-25 15:05:31

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

@Darek Kay 2015-04-24 13:34:28

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.

@user1021364 2016-07-06 09:35:44

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.

@Giancarlo Frison 2014-08-12 13:08:19

you have to cast in to array

Arrays.asList((Object[]) array)

@dVaffection 2014-11-23 18:16:40

java: incompatible types: int[] cannot be converted to java.lang.Object[]

@Nebril 2014-12-27 18:04:50

@dVaffection Then cast to int[]. Important part is to cast to an array.

Related Questions

Sponsored Content

89 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 6158124 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

58 Answered Questions

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

45 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

34 Answered Questions

[SOLVED] Create ArrayList from array

86 Answered Questions

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

28 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2555413 View
  • 3235 Score
  • 28 Answer
  • Tags:   python list

42 Answered Questions

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

26 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

28 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1895913 View
  • 2199 Score
  • 28 Answer
  • Tags:   java arrays

Sponsored Content