鍍金池/ 教程/ Linux/ Apache通用集合合并與排序
Apache Commons Collections教程
Apache通用集合開發(fā)環(huán)境
Apache通用集合過濾對象
Commons Collections簡介
Apache通用集合聯(lián)合
Apache OrderedMap接口
Apache通用集合Bag接口
Apache通用集合安全空檢查
Apache通用集合差集
Apache通用集合包函關(guān)系
Apache通用集合BidiMap接口
Apache通用集合相交
Apache通用集合轉(zhuǎn)換對象
Apache通用集合合并與排序
Apache通用集合忽略Null
Apache通用集合MapIterator接口

Apache通用集合合并與排序

Apache Commons Collections庫的CollectionUtils類提供各種實(shí)用方法,用于覆蓋廣泛用例的常見操作。 它有助于避免編寫樣板代碼。 這個庫在jdk 8之前是非常有用的,但現(xiàn)在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)

參數(shù)

  • a - 第一個集合,不能為null。
  • b - 第二個集合不能為null

返回值

  • 一個新的排序列表,其中包含集合ab的元素。

異常

  • 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 {
   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); 
   }
}

執(zhí)行上面示例代碼,得到以下結(jié)果 -

[A, B, C, D, E, F]