Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 (46k 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));

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...