user3586195
user3586195

Reputation: 498

create a list, add an element and return it to the caller in one statement

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

Answers (2)

Marcus Altman
Marcus Altman

Reputation: 1

This returns an immutable list containing the elements provided as arguments:

return List.of(elements);

Upvotes: 0

icza
icza

Reputation: 417662

Fixed-size solution

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 implements RandomAccess.

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

General solution

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

Related Questions