- Commons Collections - Discussion
- Commons Collections - Useful Resources
- Commons Collections - Quick Guide
- Commons Collections - Union
- Commons Collections - Subtraction
- Commons Collections - Intersection
- Commons Collections - Inclusion
- Commons Collections - Safe Empty Checks
- Commons Collections - Filtering Objects
- Commons Collections - Transforming Objects
- Commons Collections - Merge & Sort
- Commons Collections - Ignore Null
- Commons Collections - OrderedMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - BidiMap Interface
- Commons Collections - Bag Interface
- Commons Collections - Environment Setup
- Commons Collections - Overview
- Commons Collections - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Apache Commons Collections - Merge & Sort
CollectionUtils class of Apache Commons Collections pbrary provides various utipty methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This pbrary is very useful prior to jdk 8 as similar functionapties are now provided in Java 8 s Stream API.
Merging two sorted psts
collate() method of CollectionUtils can be used to merge two already sorted psts.
Declaration
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.collate() method −
pubpc 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
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collate() method. We ll merge two sorted psts and then print the merged and sorted pst.
import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.CollectionUtils; pubpc class CollectionUtilsTester { 8. Apache Commons Collections — Merge & Sort pubpc 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