Learn to create List
instances with only one element in it using Arrays.asList()
and Collections.singletonList()
methods.
1. Using Collections.singletonList() and List.of(): Immutable List
This is the simplest and recommended method to create an immutable List with a single element inside it. The list created with this method is also immutable, so you are sure there will not be any more elements in the list, at any condition.
List<String> list = Collections.singletonList( "data" );
Similarly, we can use the List.of() method added in Java 9.
List<String> list = List.of( "data");
For Example, you can use this list as follows.
HttpHeaders headers = new HttpHeaders();
headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON ) );
2. Using Arrays.asList(): Mutable List
This method can also help create the List
quickly, but the created list is not immutable. If you require to change this list later, 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 a single item inside it.
Happy Learning !!
Comments