- Commons Collections 教程
- Commons Collections - 主頁
- Commons Collections - 概述
- Commons Collections - 環境設定
- Commons Collections - Bag 介面
- Commons Collections - BidiMap 介面
- Commons Collections - MapIterator 介面
- Commons Collections - OrderedMap 介面
- Commons Collections - 忽略 null
- Commons Collections - 合併和排序
- Commons Collections - 轉換物件
- Commons Collections - 過濾物件
- Commons Collections - 安全空檢查
- Commons Collections - 包含
- Commons Collections - 交集
- Commons Collections - 減法
- Commons Collections - 並集
- Commons Collections 資源
- Commons Collections - 快速指南
- Commons Collections - 有用資源
- Commons Collections - 討論
Apache Commons Collections - 合併和排序
Apache Commons Collections 庫的 CollectionUtils 類為涵蓋廣泛使用案例的常見操作提供了各種實用方法。它有助於避免編寫樣板程式碼。在 jdk 8 之前,此庫非常有用,因為類似的功能現已在 Java 8 的 Stream API 中提供。
合併兩個已排序的列表
CollectionUtils 的collate()方法可用於合併兩個已排序的列表。
宣告
以下是
org.apache.commons.collections4.CollectionUtils.collate()方法的宣告−
public static <O extends Comparable<? super O>> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b)
引數
a - 第一個集合,不可為 null。
b - 第二個集合,不可為 null。
返回值
一個新的已排序 List,其中包含集合 a 和 b 的元素。
異常
NullPointerException - 如果任一集合為 null。
示例
以下示例展示了 org.apache.commons.collections4.CollectionUtils.collate() 方法的使用。我們將合併兩個已排序的列表,然後打印合並後的排序列表。
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);
}
}
輸出
輸出如下所示−
[A, B, C, D, E, F]
廣告