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]
广告
© . All rights reserved.