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?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
dazito
  • 7,740
  • 15
  • 75
  • 117
  • I'd recommend you to look here, potential duplicate: http://stackoverflow.com/questions/15213974/add-multiple-items-to-already-initialized-arraylist-in-java – axelduch Jan 24 '14 at 16:58
  • possible duplicate of [Initializing ArrayList with some predefined values](http://stackoverflow.com/questions/16194921/initializing-arraylist-with-some-predefined-values) – kosa Jan 24 '14 at 16:58

3 Answers3

5

On a single line, you can do:

list.addAll(Arrays.asList(a, b, c, d, e));
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

You can use also Guava:

 ArrayList<String> list = Lists.newArrayList(a, b, c, d, e);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
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);
omid
  • 76
  • 5