Initialize a list in Java in single line with specified value

In this post, we will see how to initialize a list in Java in single line with specified value.


 

Naive solution would be 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. Collections.nCopies() method

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

 

Download   Run Code

Output:

[1, 1, 1, 1, 1]

 

2. Java 8 – Streams

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

 

Download   Run Code

Output:

[1, 1, 1, 1, 1]

 
Above approach can work on any Object or primitive value. If we have List of Integers, we can do something like:

Download   Run Code


[1, 1, 1, 1, 1]

 

3. Using intermediate array

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

 

Download   Run Code

Output:

[1, 1, 1, 1, 1]

 
Here’s how we can do the same in single line using Java 8 Streams which can work on any Object.

 

Download   Run Code

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

 

Download   Run Code

 
Please note that all above methods produces an immutable list. In order to get a mutable instance, we need to wrap the list using ArrayList constructor. For instance,

 
 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of