0

Let's say I have the following code:

String a = " some texte";
String b = " text";
String c = "sf ";
String d = " kjel";
String e = "lkjl";

ArrayList<String> list = new ArrayList<String>();
// better way to do all these adds without having to type them all?
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);

How can I make this more efficient for both typing and computing?

2

3 Answers 3

5

On a single line, you can do:

list.addAll(Arrays.asList(a, b, c, d, e));
Sign up to request clarification or add additional context in comments.

Comments

1

in java 8 :

List<String> yourList= Arrays.asList(a,b,c,d,e);

you can make it shorter by static import: import static java.util.Arrays.asList;

in java 9 you can use list of:

List<String> yourList = List.of(a,b,c,d,e);

and in java 10 and later there is a keyword named var:

var yourList = List.of(a,b,c,d,e);

in this way yourList will be immutable so it can not be changed.

you can also use Stream:

List<String> yourList= Stream.of(a,b,c,d,e).collect(toList());

or

Stream<String>  yourList= Stream.of(a,b,c,d,e);

Comments

1

You can use also Guava:

 ArrayList<String> list = Lists.newArrayList(a, b, c, d, e);

2 Comments

+1 for Guava, although the problem here is too trivial to add a third-party library.
I agree. It is just an alternative solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.