Commons Collections 简明教程
Apache Commons Collections - Merge & Sort
Apache Commons Collections 库的 CollectionUtils 类提供各种实用方法,用于涵盖广泛使用场景的常见操作。它有助于避免编写样板代码。在 jdk 8 之前,该库非常有用,因为 Java 8 的 Stream API 中现在提供了类似的功能。
CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8’s Stream API.
Merging two sorted lists
可使用 CollectionUtils 的 collate() 方法合并两个已排序的列表。
collate() method of CollectionUtils can be used to merge two already sorted lists.
Declaration
以下是声明:
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.collate() 方法 −
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)
Return Value
一个新的已排序列表,包含集合 a 和 b 的元素。
A new sorted List, containing the elements of Collection a and b.
Example
以下示例显示 org.apache.commons.collections4.CollectionUtils.collate() 方法的用法。我们将合并两个已排序列表,然后打印已合并且已排序的列表。
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collate() method. We’ll merge two sorted lists and then print the merged and sorted list.
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionUtilsTester { 8. Apache Commons Collections — Merge & Sort
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);
}
}