[java] Converting array to list in Java

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

This question is related to java arrays list data-conversion

The answer is


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

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

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/


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 ?

_x000D_
_x000D_
    public WeatherStation[] removeElementAtIndex(WeatherStation[] array, int index)_x000D_
    {_x000D_
        List<WeatherStation> list = new ArrayList<WeatherStation>(Arrays.asList(array));_x000D_
        list.remove(index);_x000D_
        return list.toArray(new WeatherStation[0]);_x000D_
    }
_x000D_
_x000D_
_x000D_


One-liner:

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

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:


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.


Even shorter:

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

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.


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


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

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 )


In Java 8, you can use streams:

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

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[]


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

you have to cast in to array

Arrays.asList((Object[]) array)

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.


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to data-conversion

python pandas dataframe columns convert to dict key and value how to convert long date value to mm/dd/yyyy format Convert string with comma to integer How do I print bytes as hexadecimal? Convert String with Dot or Comma as decimal separator to number in JavaScript Java string to date conversion Java: How to convert List to Map How do I convert this list of dictionaries to a csv file? Converting array to list in Java Convert 4 bytes to int