Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

list

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.

like image 513
user3586195 Avatar asked Nov 10 '14 15:11

user3586195


People also ask

How do I make a list with one element?

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.

How do you add elements to an ArrayList together?

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.

Which method is used to add an element in the list?

Java List add() This method is used to add elements to the list.

How do you create and initialize an ArrayList in one line?

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.


1 Answers

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.

like image 51
icza Avatar answered Sep 30 '22 12:09

icza