Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly and conveniently create a one element arraylist [duplicate]

Is there a Utility method somewhere that can do this in 1 line? I can't find it anywhere in Collections, or List.

public List<String> stringToOneElementList(String s) {     List<String> list = new ArrayList<String>();     list.add(s);     return list; } 

I don't want to re-invent the wheel unless I plan on putting fancy rims on it.

Well... the type can be T, and not String. but you get the point. (with all the null checking, safety checks...etc)

like image 984
David T. Avatar asked Dec 03 '13 18:12

David T.


People also ask

How do you duplicate an ArrayList?

ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list. Approach: Create a list to be cloned. Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.

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 an element to an ArrayList in one line?

ArrayList<String> list = new ArrayList<String>(); list. add("A"); list. add("B"); list. add("C");


1 Answers

Fixed size List

The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T. return Arrays.asList(s); 

Variable size List

If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s)); 

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s)); 

Single Element List

Collections can return a list with a single element with list being immutable:

Collections.singletonList(s) 

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

like image 83
Elliott Frisch Avatar answered Sep 22 '22 09:09

Elliott Frisch