Create Java List with a Single Element

Learn to create a Java List with only one element in it using Arrays.asList() and Collections.singletonList() methods.

Java 10

Learn to create a Java List instance containing only one element using Arrays.asList(), Collections.singletonList() , List.of() methods and Stream API.

MethodMutabilityDescriptionJava Version
Collections.singletonList(“data”) ImmutableSimplest approach for this specific purpose. Java 1.2
List.of(“data”)ImmutableConcise syntax.Java 9+
Arrays.asList(“data”)Fixed-sizeFixed sized list. Elements cannot be added/removed. Existing elements can be modified.Java 1.2
Stream.of(“data”).collect(Collectors.toList())MutableUseful when generating lists dynamically. Java 8+

1. Collections.singletonList()

This is the simplest and most recommended method for creating an immutable list with the specified element inside it. The list created with this method is unchangeable, so you are sure there will not be any more elements in it at any condition.

List<String> list = Collections.singletonList( "data" );
System.out.println(list); // Output: [data]

For example, we can use this list as follows.

HttpHeaders headers = new HttpHeaders();
headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON ) );

2. List.of() [Java 9+]

Similarly, we can use the List.of() method added in Java 9. The List.of() method creates an immutable list with the given elements.

List<String> list = List.of( "data");
System.out.println(list); // Output: [data]

3. Arrays.asList()

The Arrays.asList method creates a fixed-size list with the given elements. The list is fixed-size, so we cannot add or remove elements; but we can modify existing ones.

List<String> list = Arrays.asList("data");
System.out.println(list); // Output: [data]

4. Stream API

We can also use Stream to collect a single element into a list. The collected list is mutable.

List<String> list = Stream.of("data").collect(Collectors.toList());
System.out.println(list); // Output: [data]

That’s all for this quick tip for creating Lists in Java containing a single item inside it.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.