0 votes
1 view
in Java by (3.9k points)

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)z

1 Answer

0 votes
by (42.6k points)

Fixed-size List

The most obvious method, that I remember of, is to build a fixed-size single element List by Arrays.asList(T...) like

// Declares a List supported by a varargs T.

return Arrays.asList(s);

Variable size List

If it requires to alter in size you can create an ArrayList and the fixed-sizeist similar

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

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

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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...