Learn to create List
instances with only one element in it using Arrays.asList()
and Collections.singletonList()
methods.
1. Using Collections.singletonList()
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" );
For Example, you can use this list as follows.
HttpHeaders headers = new HttpHeaders();
headers.setAccept( Collections.singletonList( MediaType.APPLICATION_JSON ) );
2. Using Arrays.asList()
This method can also help in creating the List
quickly, but 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