4073

Given an array of type Element[]:

Element[] array = {new Element(1), new Element(2), new Element(3)};

How do I convert this array into an object of type ArrayList<Element>?

ArrayList<Element> arrayList = ???;
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ron Tuffin
  • 53,859
  • 24
  • 66
  • 78

42 Answers42

5091
new ArrayList<>(Arrays.asList(array));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Tom
  • 55,743
  • 3
  • 27
  • 35
  • 401
    Yep. And in the (most common) case where you just want a list, the `new ArrayList` call is unecessary as well. – Calum Oct 01 '08 at 14:41
  • 163
    @Luron - just use `List list = Arrays.asList(array)` – Pool Jun 29 '11 at 15:18
  • 275
    @Calum and @Pool - as noted below in Alex Miller's answer, using `Arrays.asList(array)` without passing it into a new `ArrayList` object will fix the size of the list. One of the more common reasons to use an `ArrayList` is to be able to dynamically change its size, and your suggestion would prevent this. – Code Jockey Sep 26 '11 at 19:04
  • 15
    I'd like to point out that the new ArrayList(...) part is necessary if you want to perform mutative (like remove) operations with an iterator. – markbaldy Nov 23 '12 at 05:28
  • 147
    Arrays.asList() is a horrible function, and you should never just use its return value as is. It breaks the List template, so always use it in the form indicated here, even if it does seem redundant. Good answer. – Adam Jan 23 '13 at 03:28
  • 18
    A caveat: I just run into a misbehavior of Java 6: when Element is a primitive (e.g. the array is int[]), asList creates List . –  Feb 20 '13 at 15:48
  • 17
    @Adam `Arrays.asList()` is a very useful method when you want a list backed by a specific array. For example `Collections.shuffle(Arrays.asList(myarray))` shuffles the *original* array. – lbalazscs Feb 21 '13 at 21:13
  • 5
    @lbalazscs true, but I would say that's pretty close to a hack (even if the shuffle method was intended to be used that way), because you're basically tricking it into thinking it's dealing with a List when it's not. Handy, but I still say it's a horrible function. My argument is basically that the asList() method is misleading because it looks like it returns a List representation of the given array, when in fact it returns an only-partially-implemented List representation. – Adam Feb 22 '13 at 05:08
  • 87
    @Adam Please study the javadoc for java.util.List. The contract for add allows them to throw an UnsupportedOperationException. http://docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28E%29 Admittedly, from an object-oriented perspective it is not very nice that many times you have to know the concrete implementation in order to use a collection - this was a pragmatic design choice in order to keep the framework simple. – lbalazscs Feb 22 '13 at 09:41
  • If I have Array `a`, and convert it to ArrayList `b` using above method as `b = new ArrayList<>(Arrays.asList(a));`, I cannot retrieve an element from `b` using `b[3]`, becuase `b` contains a list? – one-hand-octopus Mar 10 '22 at 15:21
1004

Given:

Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };

The simplest answer is to do:

List<Element> list = Arrays.asList(array);

This will work fine. But some caveats:

  1. The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList. Otherwise you'll get an UnsupportedOperationException.
  2. The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.
George G
  • 7,443
  • 12
  • 45
  • 59
Alex Miller
  • 69,183
  • 25
  • 122
  • 167
400

(old thread, but just 2 cents as none mention Guava or other libs and some other details)

If You Can, Use Guava

It's worth pointing out the Guava way, which greatly simplifies these shenanigans:

Usage

For an Immutable List

Use the ImmutableList class and its of() and copyOf() factory methods (elements can't be null):

List<String> il = ImmutableList.of("string", "elements");  // from varargs
List<String> il = ImmutableList.copyOf(aStringArray);      // from array

For A Mutable List

Use the Lists class and its newArrayList() factory methods:

List<String> l1 = Lists.newArrayList(anotherListOrCollection);    // from collection
List<String> l2 = Lists.newArrayList(aStringArray);               // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs

Please also note the similar methods for other data structures in other classes, for instance in Sets.

Why Guava?

The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.

But it's not the only reason (and Java 7 isn't everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.


If You Can't...

For an Immutable List

Use the JDK's Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList():

List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));

Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList. It's an inner type, which emulates an ArrayList but actually directly references the passed array and makes it "write through" (modifications are reflected in the array).

It forbids modifications through some of the List API's methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn't truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList().

See the next step if you need a mutable list.

For a Mutable List

Same as above, but wrapped with an actual java.util.ArrayList:

List<String> l1  = new ArrayList<String>(Arrays.asList(array));    // Java 1.5 to 1.6
List<String> l1b = new ArrayList<>(Arrays.asList(array));          // Java 1.7+
List<String> l2  = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
List<String> l2b = new ArrayList<>(Arrays.asList("a", "b"));       // Java 1.7+

For Educational Purposes: The Good ol' Manual Way

// for Java 1.5+
static <T> List<T> arrayToList(final T[] array) {
  final List<T> l = new ArrayList<T>(array.length);

  for (final T s : array) {
    l.add(s);
  }
  return (l);
}

// for Java < 1.5 (no generics, no compile-time type-safety, boo!)
static List arrayToList(final Object[] array) {
  final List l = new ArrayList(array.length);

  for (int i = 0; i < array.length; i++) {
    l.add(array[i]);
  }
  return (l);
}
tagurit
  • 494
  • 5
  • 13
haylem
  • 22,460
  • 3
  • 67
  • 96
  • 32
    +1 But note that the `List` returned by `Arrays.asList` is mutable in that you can still `set` elements - it just isn't resizable. For immutable lists without Guava you might mention [`Collections.unmodifiableList`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList\(java.util.List\)). – Paul Bellora Jan 10 '13 at 02:54
254

Since this question is pretty old, it surprises me that nobody suggested the simplest form yet:

List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));

As of Java 5, Arrays.asList() takes a varargs parameter and you don't have to construct the array explicitly.

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
228
new ArrayList<T>(Arrays.asList(myArray));

Make sure that myArray is the same type as T. You'll get a compiler error if you try to create a List<Integer> from an array of int, for example.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
114

Another way (although essentially equivalent to the new ArrayList(Arrays.asList(array)) solution performance-wise:

Collections.addAll(arraylist, array);
Peter Tseng
  • 13,613
  • 4
  • 67
  • 57
  • Until Java 16 the [javadoc](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/Collections.html#addAll(java.util.Collection,T...)) stated: _The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run **significantly faster** under most implementations._ – cachius Feb 28 '23 at 03:40
  • See [this question](/q/3343766 "Why is Collections.addAll supposed to be faster than c.addAll?") for comparision discussion – cachius Feb 28 '23 at 08:48
114

Java 9

In Java 9, you can use List.of static factory method in order to create a List literal. Something like the following:

List<Element> elements = List.of(new Element(1), new Element(2), new Element(3));

This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList constructor:

new ArrayList<>(List.of(// elements vararg))

JEP 269: Convenience Factory Methods for Collections

JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List, Set, and Map interfaces in Java 9 and later.

Community
  • 1
  • 1
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • 1
    List.of() will not return an instance of java.util.ArrayList, as requested in the original question. Therefore only the second option is a valid answer. – tquadrat Jul 05 '19 at 12:31
94

You probably just need a List, not an ArrayList. In that case you can just do:

List<Element> arraylist = Arrays.asList(array);
Kip
  • 107,154
  • 87
  • 232
  • 265
  • 8
    That will be backed by the original input array, which is why you (probably) want to wrap it in a new ArrayList. – Bill the Lizard Oct 01 '08 at 14:46
  • 17
    Be careful with this solution. If you look, Arrays ISN'T returning a true java.util.ArrayList. It's returning an inner class that implements the required methods, but you cannot change the memebers in the list. It's merely a wrapper around an array. – Mikezx6r Oct 01 '08 at 14:47
  • 1
    You can cast the List item to an ArrayList – monksy Oct 09 '09 at 22:48
  • 13
    @Mikezx6r: little **correction**: it's a fixed-size list. You can change the elements of the list (`set` method), you cannot change the size of the list (not `add` or `remove` elements)! – user85421 Dec 04 '09 at 13:10
  • 1
    Yes, with the caveat that it depends on what you want to do with the list. It's worth notng that if the OP simply wants to iterate through the elements, the array doesn't have to be converted at all. – PaulMurrayCbr May 05 '13 at 09:23
  • 1
    @monksy No, you can't. As was said, it is a different kind of `ArrayList`. – glglgl Feb 22 '15 at 17:05
  • This does not work if array element is of primitive type in Java 8. For details, see http://stackoverflow.com/q/2607289/431698 – Jingguo Yao Feb 04 '16 at 07:05
78

Another update, almost ending year 2014, you can do it with Java 8 too:

ArrayList<Element> arrayList = Stream.of(myArray).collect(Collectors.toCollection(ArrayList::new));

A few characters would be saved, if this could be just a List

List<Element> list = Stream.of(myArray).collect(Collectors.toList());
yamilmedina
  • 3,315
  • 2
  • 20
  • 28
  • 10
    It's probably best not to be implementation-dependent, but `Collectors.toList()` actually returns an `ArrayList`. – bcsb1001 Dec 31 '14 at 19:55
  • incorrect use of Stream.of(...); that will create a one element stream. Use Arrays.stream instead – Patrick Parker Nov 18 '16 at 11:59
  • I don't think so, the 2 options are valid but the Arrays.stream is slightly 'better' since you can create it with fixed size, using the overload method with 'start', 'end' args. See also: http://stackoverflow.com/a/27888447/2619091 – yamilmedina Nov 30 '16 at 21:45
49

If you use :

new ArrayList<T>(Arrays.asList(myArray));

you may create and fill two lists ! Filling twice a big list is exactly what you don't want to do because it will create another Object[] array each time the capacity needs to be extended.

Fortunately the JDK implementation is fast and Arrays.asList(a[]) is very well done. It create a kind of ArrayList named Arrays.ArrayList where the Object[] data points directly to the array.

// in Arrays
@SafeVarargs
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}
//still in Arrays, creating a private unseen class
private static class ArrayList<E>

    private final E[] a;    
    ArrayList(E[] array) {
        a = array; // you point to the previous array
    }
    ....
}

The dangerous side is that if you change the initial array, you change the List ! Are you sure you want that ? Maybe yes, maybe not.

If not, the most understandable way is to do this :

ArrayList<Element> list = new ArrayList<Element>(myArray.length); // you know the initial capacity
for (Element element : myArray) {
    list.add(element);
}

Or as said @glglgl, you can create another independant ArrayList with :

new ArrayList<T>(Arrays.asList(myArray));

I love to use Collections, Arrays, or Guava. But if it don't fit, or you don't feel it, just write another inelegant line instead.

Nicolas Zozol
  • 6,910
  • 3
  • 50
  • 74
  • 1
    I fail to see the fundamental difference between your loop at the end of the answer and the `new ArrayList(Arrays.asList(myArray));` part which you discourage to use. Both do quite the same and have the same complexity. – glglgl Feb 22 '15 at 17:03
  • The Collections one create a pointer at the beginning of the array. My loop create many pointers : one for each array member. So if the original array changes, my poiners are still directed toward the former values. – Nicolas Zozol Feb 22 '15 at 19:59
  • 1
    `new ArrayList(Arrays.asList(myArray));` does the same, it copies the `asList` to an `ArrayList`... – glglgl Feb 22 '15 at 21:56
42

In Java 9 you can use:

List<String> list = List.of("Hello", "World", "from", "Java");
List<Integer> list = List.of(1, 2, 3, 4, 5);
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
MarekM
  • 1,426
  • 17
  • 14
37

According with the question the answer using java 1.7 is:

ArrayList<Element> arraylist = new ArrayList<Element>(Arrays.<Element>asList(array));

However it's better always use the interface:

List<Element> arraylist = Arrays.<Element>asList(array);
nekperu15739
  • 3,311
  • 2
  • 26
  • 25
34
// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray); 
Bohdan
  • 16,531
  • 16
  • 74
  • 68
28

Since Java 8 there is an easier way to transform:

import java.util.List;    
import static java.util.stream.Collectors.toList;

public static <T> List<T> fromArray(T[] array) {
    return Arrays.stream(array).collect(toList());
}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • I don't see how this is easier than: new ArrayList<>(Arrays.asList(array)); It's also unclear that it is more efficient in any way.. – AminM Aug 10 '23 at 15:57
27

You can convert using different methods

  1. List<Element> list = Arrays.asList(array);

  2. List<Element> list = new ArrayList();
    Collections.addAll(list, array);

  3. Arraylist list = new Arraylist();
    list.addAll(Arrays.asList(array));

For more detail you can refer to http://javarevisited.blogspot.in/2011/06/converting-array-to-arraylist-in-java.html

Draken
  • 3,134
  • 13
  • 34
  • 54
js_248
  • 2,032
  • 4
  • 27
  • 38
25

as all said this will do so

 new ArrayList<>(Arrays.asList("1","2","3","4"));

and the common newest way to create array is observableArrays

ObservableList: A list that allows listeners to track changes when they occur.

for Java SE you can try

FXCollections.observableArrayList(new Element(1), new Element(2), new Element(3));

that is according to Oracle Docs

observableArrayList() Creates a new empty observable list that is backed by an arraylist. observableArrayList(E... items) Creates a new observable array list with items added to it.

Update Java 9

also in Java 9 it's a little bit easy:

List<String> list = List.of("element 1", "element 2", "element 3");
jemystack
  • 408
  • 7
  • 12
23

You also can do it with stream in Java 8.

 List<Element> elements = Arrays.stream(array).collect(Collectors.toList()); 
Vaseph
  • 704
  • 1
  • 8
  • 20
  • 3
    As of **java 8**, `Collectors.toList()` will return an `ArrayList`. However this may differ in future versions on java.If you want a specific type of collection then use `Collectors.toCollection()` instead where you can specify which exact type of collection you would want to create. – Raja Anbazhagan Feb 04 '19 at 11:08
18
  1. If we see the definition of Arrays.asList() method you will get something like this:

     public static <T> List<T> asList(T... a) //varargs are of T type. 
    

    So, you might initialize arraylist like this:

     List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
    

    Note : each new Element(int args) will be treated as Individual Object and can be passed as a var-args.

  2. There might be another answer for this question too.
    If you see declaration for java.util.Collections.addAll() method you will get something like this:

    public static <T> boolean addAll(Collection<? super T> c, T... a);
    

    So, this code is also useful to do so

    Collections.addAll(arraylist, array);
    
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
14

If the array is of a primitive type, the given answers won't work. But since Java 8 you can use:

int[] array = new int[5];
Arrays.stream(array).boxed().collect(Collectors.toList());
Unheilig
  • 16,196
  • 193
  • 68
  • 98
A1m
  • 2,897
  • 2
  • 24
  • 39
12

Another simple way is to add all elements from the array to a new ArrayList using a for-each loop.

ArrayList<Element> list = new ArrayList<>();

for(Element e : array)
    list.add(e);
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
9

Even though there are many perfectly written answers to this question, I will add my inputs.

Say you have Element[] array = { new Element(1), new Element(2), new Element(3) };

New ArrayList can be created in the following ways

ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<>(
    Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));

// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);

And they very well support all operations of ArrayList

arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success

But the following operations returns just a List view of an ArrayList and not actual ArrayList.

// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));

Therefore, they will give error when trying to make some ArrayList operations

listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error

More on List representation of array link.

Community
  • 1
  • 1
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
9

Simplest way to do so is by adding following code. Tried and Tested.

String[] Array1={"one","two","three"};
ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));
Hemin
  • 712
  • 1
  • 14
  • 29
9

You can do it in java 8 as follows

ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());
Ron Tuffin
  • 53,859
  • 24
  • 66
  • 78
Adit A. Pillai
  • 647
  • 1
  • 10
  • 22
  • 2
    Downvoted because that cast looks very dangerous. nothing specifies that the type of list that is returned is actually an ArrayList, as the javadoc states: "There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned" – Dorian Gray Jul 03 '18 at 17:45
  • 1
    If you want to explicitely create an ArrayList, try this: `ArrayList list = Arrays.stream(array).collect(Collectors.toCollection(ArrayList::new));` – Dorian Gray Aug 03 '18 at 20:53
9

Another Java8 solution (I may have missed the answer among the large set. If so, my apologies). This creates an ArrayList (as opposed to a List) i.e. one can delete elements

package package org.something.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Junk {

    static <T> ArrayList<T>  arrToArrayList(T[] arr){
        return Arrays.asList(arr)
            .stream()
            .collect(Collectors.toCollection(ArrayList::new));
    }

    public static void main(String[] args) {
        String[] sArr = new String[]{"Hello", "cruel", "world"};
        List<String> ret = arrToArrayList(sArr);
        // Verify one can remove an item and print list to verify so
        ret.remove(1);
        ret.stream()
            .forEach(System.out::println);
    }
}

Output is...
Hello
world

Toothless Seer
  • 798
  • 9
  • 13
9

We can easily convert an array to ArrayList. We use Collection interface's addAll() method for the purpose of copying content from one list to another.

 Arraylist arr = new Arraylist();
 arr.addAll(Arrays.asList(asset));
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
rashedcs
  • 3,588
  • 2
  • 39
  • 40
9

Use the following code to convert an element array into an ArrayList.

Element[] array = {new Element(1), new Element(2), new Element(3)};

ArrayList<Element>elementArray=new ArrayList();
for(int i=0;i<array.length;i++) {
    elementArray.add(array[i]);
}
Pang
  • 9,564
  • 146
  • 81
  • 122
8

Given Object Array:

Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};

Convert Array to List:

    List<Element> list = Arrays.stream(array).collect(Collectors.toList());

Convert Array to ArrayList

    ArrayList<Element> arrayList = Arrays.stream(array)
                                       .collect(Collectors.toCollection(ArrayList::new));

Convert Array to LinkedList

    LinkedList<Element> linkedList = Arrays.stream(array)
                     .collect(Collectors.toCollection(LinkedList::new));

Print List:

    list.forEach(element -> {
        System.out.println(element.i);
    });

OUTPUT

1

2

3

Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
6

Already everyone has provided enough good answer for your problem. Now from the all suggestions, you need to decided which will fit your requirement. There are two types of collection which you need to know. One is unmodified collection and other one collection which will allow you to modify the object later.

So, Here I will give short example for two use cases.

  • Immutable collection creation :: When you don't want to modify the collection object after creation

    List<Element> elementList = Arrays.asList(array)

  • Mutable collection creation :: When you may want to modify the created collection object after creation.

    List<Element> elementList = new ArrayList<Element>(Arrays.asList(array));

Sumit Das
  • 311
  • 3
  • 6
  • List elementList = Arrays.asList(array) creates a wrapper over the original array which makes original array available as List. Hence a wrapper object is created, nothing gets copied from the original array. Therefore, operations like add or remove elements are not allowed. – Priyanka Sep 09 '17 at 08:57
  • 4
    Note that your "immutable collection" is not really immutable - the `List` returned by `Arrays.asList` is just a wrapper over the original array, and allows individual items to be accessed and modified via `get` and `set`. You should probably clarify that you mean "not add or remove elements" instead of "immutable", which means to not change at all. – Tamoghna Chowdhury Oct 06 '17 at 20:24
6

Java 8’s Arrays class provides a stream() method which has overloaded versions accepting both primitive arrays and Object arrays.

/**** Converting a Primitive 'int' Array to List ****/

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

List<Integer> integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());

/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/

List<Integer> integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());

/**** Converting an 'Integer' Array to List ****/

Integer integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

List<Integer> integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());
sanyassh
  • 8,100
  • 13
  • 36
  • 70
Himanshu Dave
  • 119
  • 1
  • 9
6

You could also use polymorphism to declare the ArrayList while calling the Arrays-interface as following:

List<Element> arraylist = new ArrayList<Integer>(Arrays.asList(array));

Example:

Integer[] array = {1};    // autoboxing
List<Integer> arraylist = new ArrayList<Integer>(Arrays.asList(array));

This should work like a charm.

Manifest Man
  • 873
  • 10
  • 16
4

Below code seems nice way of doing this.

new ArrayList<T>(Arrays.asList(myArray));
Singh123
  • 216
  • 3
  • 10
4

Hi you can use this line of code , and it's the simplest way

 new ArrayList<>(Arrays.asList(myArray));

or in case you use Java 9 you can also use this method:

List<String> list = List.of("Hello", "Java"); 
List<Integer> list = List.of(1, 2, 3);
Chris
  • 806
  • 1
  • 10
  • 17
4

For normal size arrays, above answers hold good. In case you have huge size of array and using java 8, you can do it using stream.

  Element[] array = {new Element(1), new Element(2), new Element(3)};
  List<Element> list = Arrays.stream(array).collect(Collectors.toList());
Sandip Jangra
  • 145
  • 2
  • 9
3

In java there are mainly 3 methods to convert an array to an arrayList

  1. Using Arrays.asList() method : Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

    List<String> list = Arrays.asList(array);                   
    System.out.println(list);
    
  2. Collections.addAll() method - Create a new list before using this method and then add array elements using this method to existing list.

     List<String> list1 = new ArrayList<String>();
     Collections.addAll(list1, array);
     System.out.println(list1);
    
  3. Iteration method - Create a new list. Iterate the array and add each element to the list.

     List<String> list2 = new ArrayList<String>();
     for(String text:array) {
         list2.add(text);
     }
     System.out.println(list2);
    

you can refer this document too

3

You can use the following 3 ways to create ArrayList from Array.

  String[] array = {"a", "b", "c", "d", "e"};

  //Method 1
  List<String> list = Arrays.asList(array);          

  //Method 2
  List<String> list1 = new ArrayList<String>();
  Collections.addAll(list1, array);

  //Method 3
  List<String> list2 = new ArrayList<String>();
  for(String text:array) {
     list2.add(text);
  }
Hasee Amarathunga
  • 1,901
  • 12
  • 17
3

There is one more way that you can use to convert the array into an ArrayList. You can iterate over the array and insert each index into the ArrayList and return it back as in ArrayList.

This is shown below.

public static void main(String[] args) {
        String[] array = {new String("David"), new String("John"), new String("Mike")};

        ArrayList<String> theArrayList = convertToArrayList(array);
    }

    private static ArrayList<String> convertToArrayList(String[] array) {
        ArrayList<String> convertedArray = new ArrayList<String>();

        for (String element : array) {
            convertedArray.add(element);
        }

        return convertedArray;
    }
2

You can create an ArrayList using Cactoos (I'm one of the developers):

List<String> names = new StickyList<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

There is no guarantee that the object will actually be of class ArrayList. If you need that guarantee, do this:

ArrayList<String> list = new ArrayList<>(
  new StickyList<>(
    "Scott Fitzgerald", "Fyodor Dostoyevsky"
  )
);
yegor256
  • 102,010
  • 123
  • 446
  • 597
2

the lambda expression that generates a list of type ArrayList<Element>
(1) without an unchecked cast
(2) without creating a second list (with eg. asList())

ArrayList<Element> list = Stream.of( array ).collect( Collectors.toCollection( ArrayList::new ) );

Kaplan
  • 2,572
  • 13
  • 14
1

With Stream (since java 16)

new ArrayList<>(Arrays.stream(array).toList());

Edgar Civil
  • 31
  • 1
  • 5
1

I've used the following helper method on occasions when I'm creating a ton of ArrayLists and need terse syntax:

import java.util.ArrayList;
import java.util.Arrays;

class Main {

    @SafeVarargs
    public static <T> ArrayList<T> AL(T ...a) {
        return new ArrayList<T>(Arrays.asList(a));
    }

    public static void main(String[] args) {
        var al = AL(AL(1, 2, 3, 4), AL(AL(5, 6, 7), AL(8, 9)));
        System.out.println(al); // => [[1, 2, 3, 4], [[5, 6, 7], [8, 9]]]
    }
}

Guava uses the same approach so @SafeVarargs appears to be safe here. See also Java SafeVarargs annotation, does a standard or best practice exist?.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
1
Element[] array = {new Element(1), new Element(2), new Element(3)};

List<Element> list = List.of(array);

or

List<Element> list = Arrays.asList(array);

both ways we can convert it to a list.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
neha
  • 62
  • 5
0

Use below code

Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);
Devratna
  • 938
  • 1
  • 7
  • 26