Learn to create a Java List instance containing only one element using Arrays.asList(), Collections.singletonList() , List.of() methods and Stream API.
Method | Mutability | Description | Java Version |
---|---|---|---|
Collections.singletonList(“data”) | Immutable | Simplest approach for this specific purpose. | Java 1.2 |
List.of(“data”) | Immutable | Concise syntax. | Java 9+ |
Arrays.asList(“data”) | Fixed-size | Fixed sized list. Elements cannot be added/removed. Existing elements can be modified. | Java 1.2 |
Stream.of(“data”).collect(Collectors.toList()) | Mutable | Useful 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 !!
Comments