0

I have 3 list in Java and how do I merge them?

list1 = [10,20,30]
list2 = [40,50,60]
list3 = [70]

Output

res = [10,40,70,20,50,30,60]

I'm familiar with writing a achieving the result but would like to know if there is any libraries that I can use it.

user1050619
  • 19,822
  • 85
  • 237
  • 413

3 Answers3

1
res = ArrayUtils.addAll(list1, list2);
res = ArrayUtils.addall(res,list3);

Also, see many more options on how to do this here.

Community
  • 1
  • 1
barq
  • 3,681
  • 4
  • 26
  • 39
0

from How to mix two arrays in Java?

int[] merge(int[]... arrays) {
    int length = 0;
    for (int[] a: arrays) {
        length += a.length;
    }
    int result[] = new int[length];
    for (int i = 0, j = 0; j < length; ++i) {
        for (int[] a: arrays) {
            if (i < a.length) {
                result[j++] = a[i];
            }
        }
    }
    return result;
}

then simply

merge(list1, list2, list3)
Community
  • 1
  • 1
user2291758
  • 715
  • 8
  • 19
0

You can use the normal Java 7 libraries:

List result = new ArrayList();
result.addAll(list1); result.addAll(list2); result.addAll(list3);`

or shorter:

List result = new ArrayList();
Collections.addAll(result, list1, list2, list3);

I guess there is also a Java 8 stream solution.

eckes
  • 10,103
  • 1
  • 59
  • 71