This post will discuss how to initialize a list in Java in a single line with the specified value.

A naive solution is to call the List.add() method n times in a loop, where n is the specified size of the list. This works fine, but there are better ways, as discussed below:

1. Using Collections.nCopies() method

Java collection framework has provided the Collections.nCopies() method, which returns an immutable list consisting of the specified copies of the specified object. The object allocated by this method holds a single reference to the specified object; hence its memory consumption is very less.

Download  Run Code

2. Using Java 8 Stream

We can also use Java 8 Stream for this. The idea is to use the Stream.generate() method, which takes a Supplier. In the following example, we have created an infinite stream of empty character sequence, which is limited by using the limit() method. Finally, each element is mapped to the specified value and collected in an immutable list.

Download  Run Code

 
The above approach can work on any object or a primitive value. If we have a list of Integer, we can do something like:

Download  Run Code


[1, 1, 1, 1, 1]

 
This is equivalent to:

Download  Run Code


[1, 1, 1, 1, 1]

3. Using intermediate array

Well, this is not a single liner, but worth mentioning. The idea is to create an array of the specified size and use Arrays.fill() to initialize it by the given value. Then we pass this array to the Arrays.asList() method to get an immutable list.

Download  Run Code

 
Here’s how we can do the same in a single line using Java 8 Stream, which can work on any object.

Download  Run Code

 
We can also use Arrays.stream() or Stream.of() with map() method.

Download  Run Code

 
Please note that all the above-mentioned methods produce an immutable list. To get a mutable instance, we need to wrap the list using the ArrayList constructor. For instance,

That’s all about initializing a list in Java in a single line with the specified value.