Initialization of an ArrayList in one line
Actually, probably the "best" way to initialize the ArrayList
is the method you wrote, as it does not need to create a new List
in any way:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
The catch is that there is quite a bit of typing required to refer to that list
instance.
There are alternatives, such as making an anonymous inner class with an instance initializer (also known as an "double brace initialization"):
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
However, I'm not too fond of that method because what you end up with is a subclass of ArrayList
which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
What would have been nice was if the Collection Literals proposal for Project Coin was accepted (it was slated to be introduced in Java 7, but it's not likely to be part of Java 8 either.):
List<String> list = ["A", "B", "C"];
Unfortunately it won't help you here, as it will initialize an immutable List
rather than an ArrayList
, and furthermore, it's not available yet, if it ever will be.
Initializing an ArrayList with an array in a single line
You can use Arrays.asList
method, which takes a var-args
, and returns a fixed-size List
backed by an array. So, you can't add any element to this list. Further, any modification done to the elements of the List
will be reflected back in the array
.
String[] arrayOfStrings = {"this", "is", "an", "array", "of", "strings"};
List<String> list = Arrays.asList(arrayOfStrings);
or: -
List<String> list = Arrays.asList("this", "is", "an", "array", "of", "strings");
If you want to increase the size of this list, you would have to pass it in ArrayList
constructor.
List<String> list = new ArrayList<String>(Arrays.asList(arrayOfStrings));
How to initialize List<Short> in one line?
Use Integer.shortValue()
method: Like below
List<Short> numbers = Stream.of(1, 2, 3, 4, 5).map(value -> value.shortValue()).collect(Collectors.toList());
How to Create and Initialize (in Java) a List<String[]> in the same statement? (Editors please NOTE: this *not* the same as just a List<String>)
The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.
to create a mutable list
final List<String[]> rolesCsv =
new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));
Otherwise (despite the array, its element, will not be immutable)
final List<String[]> rolesCsv =
Collections.singletonList(new String[]{"Role Name","Description"})
Initialize new arraylist with (custom) items in one line in Kotlin
arrayListOf(items)
So you can just do
arrayListOf(MyCustomItem(1), MyCustomItem(2))
How to declare an ArrayList with values?
In Java 9+ you can do:
var x = List.of("xyz", "abc");
// 'var' works only for local variables
Java 8 using Stream
:
Stream.of("xyz", "abc").collect(Collectors.toList());
And of course, you can create a new object using the constructor that accepts a Collection
:
List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList
class:
ArrayList()
Constructs an empty list with an initial capacity of ten.
ArrayList(Collection<? extends E> c)
(*)Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
ArrayList(int initialCapacity)
Constructs an empty list with the specified initial capacity.
How to initialize ArrayList<Double> in one line from a list of mixed integer and float?
You can do this with a DoubleStream
:
public static ArrayList<Double> Foo() {
return DoubleStream.of(1.0, 2, 3.1, 4, 5)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
}
How to initialize List Of List in one line
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2), Arrays.asList(3,4));
In Java 9+ you can replace Arrays.asList()
with List.of()
:
List<List<Integer>> list = List.of(List.of(1,2), List.of(3,4));
Related Topics
System.Currenttimemillis VS System.Nanotime
Difference Between a Static and a Non-Static Initialization Code Block
How to Use Different Certificates on Specific Connections
How to Increase the Java Stack Size
Difference Between Inheritance and Composition
How to Establish a Connection Pool in Jdbc
How to Add New Elements to an Array
Why Is There No Sortedlist in Java
Convert Arraylist≪String≫ to String[] Array
When Does System.Gc() Do Something
Intellij Can't Recognize Javafx 11 With Openjdk 11
How to Run Unix Shell Script from Java Code
Quality of Image After Resize Very Low - Java