Reputation: 498
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.
Upvotes: 5
Views: 6726
Reputation: 1
This returns an immutable list containing the elements provided as arguments:
return List.of(elements);
Upvotes: 0
Reputation: 417662
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.
Upvotes: 12