1

Is there a method to concatenate multiple ArrayLists?

ex:

ArrayList<Integer> a
ArrayList<Integer> b
ArrayList<Integer> c

ArrayList<Integer> d = a + b + c

where d is a single ArrayList<Integer> that contains all of the values of a,b,c in their preserved orders

jmj
  • 225,392
  • 41
  • 383
  • 426
Liondancer
  • 13,368
  • 38
  • 121
  • 222

3 Answers3

6

Use addAll() method

d.addAll(a);
d.addAll(b);
d.addAll(c);
jmj
  • 225,392
  • 41
  • 383
  • 426
2

It is an unfortunate aspect of the collections framework that there is no built in list algebra, but things like Guava can provide methods that act like operators of the type you want. Straight up java runtime library code would look like

List< Integer > d = new ArrayList<>( a );
d.addAll( b );
d.addAll( c );
Judge Mental
  • 5,091
  • 15
  • 20
2

addAll method and an ArrayList constructor will do the trick. (There is no operator overriding in Java)

ArrayList<Integer> d = new ArrayList<Integer>(a);
d.addAll(b);
d.addAll(c);

Note that you can declare all your variables as List or Collection which is a better practice. That way you are stuck to ArrayList as a Collection implementation.

Collection<Integer> d = new ArrayList<Integer>(a);
C.Champagne
  • 4,706
  • 2
  • 21
  • 32