Is there a way to create a list and add an element and return the resulting list in one statement ?
return new ArrayList<Email>().add(email);
Above does not work for obvious reasons. Thanks.
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.
ArrayList implements the List<E> Interface. To add an element to the end of an ArrayList use: boolean add( E elt ) ; // Add a reference to an object elt to the end of the ArrayList, // increasing size by one.
Java List add() This method is used to add elements to the list.
Actually, probably the "best" way to initialize the ArrayList is the method you wrote, as it does not need to create a new List in any way: ArrayList<String> list = new ArrayList<String>(); list. add("A"); list. add("B"); list.
Try:
return Arrays.asList(email);
Note that the returned list will be fixed size. Quoting from the javadoc:
Returns a fixed-size list backed by the specified array. This method acts as bridge between array-based and collection-based APIs, in combination with
Collection.toArray()
. The returned list is serializable and implementsRandomAccess
.
So you can change elements in the returned List
, but you cannot perform operations which change its size.
See this example:
String email = "[email protected]";
List<String> list = Arrays.asList(email);
list.set(0, "[email protected]"); // OK
list.clear(); // throws UnsupportedOperationException
list.add("[email protected]"); // throws UnsupportedOperationException
If you need to make the returned list completely modifiable, you can still do it in one line:
return new ArrayList<>(Arrays.asList(email));
So basically just create a new ArrayList
initialized with the fixed-size list created by Arrays.asList()
. Although this isn't really idiomatic to how a List
with one element should be created, it solves your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With