This post will discuss how to create a fixed-size List in Java.

1. Using Array.asList() method

To get a fixed-size list, you can simply create and pass the corresponding type array to the Array.asList() method. This will result in a fixed-size list that is backed by the specified array. This is demonstrated below:

Download  Run Code

Output:

[null, null, null, null, null, null, null, null, null, null]

 
Note that any structural changes made to the list (that change the size of the list) throw java.lang.UnsupportedOperationException. To add/remove elements from the list, you can wrap the fixed-size list using the ArrayList constructor. For instance,

Download  Run Code

Output:

9

2. Using Stream API

Here’s a similar approach using the Stream API. It takes advantage of the Arrays.stream() method, which can accept a primitive array and returns a sequential IntStream.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 
To get an unmodifiable list, you can use the Collectors.toUnmodifiableList() collector.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

3. Using Collections.nCopies() method

Alternatively, you can use the Collections.nCopies() method to get an immutable list consisting of specified copies of the supplied item. Be careful using this method on mutable objects, as the same instance of an object will be copied to all the available slots.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 
The above code also throws java.lang.UnsupportedOperationException on adding or removing elements from it. To facilitate structural changes to the list, convert the list into an ArrayList.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

4. Using IntStream

The idea here is to generate an infinite sequential ordered IntStream, limit it with the required size, and map it to some default value. Finally, collect the elements into a list.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 
Java 9 offers a more flexible version of the IntStream.iterate() method that can terminate the stream without the need for the limit() method.

Download  Run Code

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

That’s all about creating a fixed-size List in Java.