Reputation: 54588
Element[] array = {new Element(1), new Element(2), new Element(3)};
How do I convert the above variable of type Element[]
into a variable of type ArrayList<Element>
?
ArrayList<Element> arrayList = ...;
Upvotes: 4120
Views: 1876776
Reputation: 2005
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);
}
Upvotes: 3
Reputation: 721
In java there are mainly 3 methods to convert an array to an arrayList
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);
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);
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
Upvotes: 3
Reputation: 164
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());
Upvotes: 5
Reputation: 824
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);
Upvotes: 5
Reputation: 5181
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
Upvotes: 9
Reputation: 3725
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));
Upvotes: 10
Reputation: 712
You also can do it with stream in Java 8.
List<Element> elements = Arrays.stream(array).collect(Collectors.toList());
Upvotes: 24
Reputation: 420
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.
also in Java 9 it's a little bit easy:
List<String> list = List.of("element 1", "element 2", "element 3");
Upvotes: 26
Reputation: 56312
You can use the following instruction:
new ArrayList<>(Arrays.asList(array));
Upvotes: 5139
Reputation: 60
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.
Upvotes: 1
Reputation: 56845
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?.
Upvotes: 1
Reputation: 71
With Stream (since java 16)
new ArrayList<>(Arrays.stream(array).toList());
Upvotes: 2
Reputation: 22663
(old thread, but just 2 cents as none mention Guava or other libs and some other details)
It's worth pointing out the Guava way, which greatly simplifies these shenanigans:
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
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
.
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.
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.
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 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);
}
Upvotes: 403
Reputation: 905
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.
Upvotes: 6
Reputation: 750
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;
}
Upvotes: 3
Reputation: 10751
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());
}
Upvotes: 28
Reputation: 6836
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 avar-args
.
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);
Upvotes: 18
Reputation: 216
Below code seems nice way of doing this.
new ArrayList<T>(Arrays.asList(myArray));
Upvotes: 4
Reputation: 3718
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 ) );
Upvotes: 2
Reputation: 119
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());
Upvotes: 6
Reputation: 1008
Use below code
Element[] array = {new Element(1), new Element(2), new Element(3)};
ArrayList<Element> list = (ArrayList) Arrays.asList(array);
Upvotes: 0
Reputation: 247
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]);
}
Upvotes: 8
Reputation: 48113
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 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.
Upvotes: 115
Reputation: 1466
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);
Upvotes: 42
Reputation: 667
You can do it in java 8 as follows
ArrayList<Element> list = (ArrayList<Element>)Arrays.stream(array).collect(Collectors.toList());
Upvotes: 9
Reputation: 311
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));
Upvotes: 6
Reputation: 3107
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());
Upvotes: 14
Reputation: 105023
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"
)
);
Upvotes: 2
Reputation: 838
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
Upvotes: 9
Reputation: 752
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));
Upvotes: 9