Commons Collection Interfaces
- Commons Collections - Bag Interface
- Commons Collections - BidiMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - OrderedMap Interface
Commons Collections Usage
- Commons Collections - Ignore Null
- Commons Collections - Merge & Sort
- Commons Collections - Transforming Objects
- Commons Collections - Filtering Objects
- Commons Collections - Safe Empty Checks
- Commons Collections - Inclusion
- Commons Collections - Intersection
- Commons Collections - Subtraction
- Commons Collections - Union
Commons Collections Resource
Apache Commons Collections - Merging Sorted Data
Merging two sorted lists
Syntax
collate() method of CollectionUtils can be used to merge two already sorted lists.
List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2);
Declaration
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.collate() method −
public static <O extends Comparable<? super O>> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b)
Parameters
a − The first collection, must not be null.
b − The second collection, must not be null.
Return Value
A new sorted List, containing the elements of Collection a and b.
Exception
NullPointerException − If either collection is null.
Example - Merging two sorted Lists
The following example shows the usage of collate() method. We'll merge two sorted lists and then print the merged and sorted list.
CommonCollectionsTester.java
package com.tutorialspoint;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CommonCollectionsTester {
public static void main(String[] args) {
List<String> sortedList1 = Arrays.asList("A","C","E");
List<String> sortedList2 = Arrays.asList("B","D","F");
List<String> mergedList = CollectionUtils.collate(sortedList1, sortedList2);
System.out.println(mergedList);
}
}
Output
The output is as follows −
[A, B, C, D, E, F]
Advertisements