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.

1
  • "I'm familiar with...", can you give us an example of what you normally do? Commented Feb 12, 2015 at 21:40

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

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) 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.