Create List with Single Element

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

Using Collections.singletonList() Method [ Immutable List ]

This is simplest and recommended method to create immutable List with single element inside it. The list created with this method is immutable as well, so you are sure that there will not be any more elements in list, at any condition.

List<String> list = Collections.singletonList( "data" );   //How to create

For Example, you can use this list as follows.

HttpHeaders headers = new HttpHeaders();

headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON ) );	//How to use

Using Arrays.asList() Method

This method can also help in creating the List quickly, but created list is not immutable. If you are not planning to have this list immutable, then use this method.

List<String> list = Arrays.asList( "data");

For Example, you can use this list as follows.

HttpHeaders headers = new HttpHeaders();

headers.setAccept( Arrays.asList( MediaType.APPLICATION_JSON ) );	

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

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.