Apache Common Collections API provide a facility to merge two sorted collections. This post will show how to use it with an example
Main Code
1 import java.util.ArrayList;
2 import java.util.List;
3
4 import org.apache.commons.collections4.CollectionUtils;
5
6 public class Example3 {
7 public static void main(String[] args) {
8 List list1 = new ArrayList();
9 List list2 = new ArrayList();
10
11 list1.add(1);
12 list1.add(2);
13 list1.add(3);
14 list1.add(4);
15 list1.add(5);
16
17 list2.add(6);
18 list2.add(7);
19 list2.add(8);
20 list2.add(9);
21 list2.add(10);
22
23 List list = CollectionUtils.collate(list1, list2);
24
25 for(Integer data : list) {
26 System.out.println(data);
27 }
28 }
29 }
Explanation
In the above code we create two sorted lists named list1 and list2 and populate them.
Next we call collate method of CollectionUtils utililty class and pass the two list as arguments. Refer to line 23.
They are other overloaded versions of collate. You can know more about them at Apache Common Collections javadoc.