Reputation: 7980
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?
Upvotes: 0
Views: 312
Reputation: 96
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);
Upvotes: 1
Reputation: 53829
You can use also Guava:
ArrayList<String> list = Lists.newArrayList(a, b, c, d, e);
Upvotes: 1
Reputation: 62864
On a single line, you can do:
list.addAll(Arrays.asList(a, b, c, d, e));
Upvotes: 5