java - 有没有可以合并两个排序数组的实用程序?
问题描述
我想知道是否有一些实用程序(库)可以在 1 行中合并两个排序数组。
解决方案
CollectionUtils.collate
从 Apache Commons使用。
从文档中:
将两个排序的集合 a 和 b 合并到一个排序的 List 中,以便保留元素的自然顺序。使用标准 O(n) 合并算法来合并两个排序列表。
这是一个例子
import static java.util.Arrays.asList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class MergeSortedArrays {
public static void main(String[] args) {
Integer a[] = new Integer[]{2, 4, 6, 8, 10};
Integer b[] = new Integer[]{1, 3, 4, 5, 6};
List<Integer> merged = CollectionUtils.collate(asList(a), asList(b));
}
}
该库还提供了一些更有用的重载
// 1. discards duplicates
static <O extends Comparable<? super O>> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, boolean includeDuplicates)
// 2. uses a custom comparator
static <O> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)
// 3. uses a custom comparator and discards duplicates
static <O> List<O> collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c, boolean includeDuplicates)
推荐阅读
- python - 对已关闭文件的 I/O 操作。与熊猫
- php - 如何将 Symfony HttpClient 模拟为依赖项?
- python - Tensor(..., shape=(), dtype=int64) 必须与 Tensor(..., shape=(), dtype=resource) Keras 来自同一个图
- delphi - delphi用TStringList模拟fifo
- angular - 将 NGXS 状态分解为更小的可维护部分,但让它们彼此可访问的最佳方法是什么?
- c - 我在学习编程语言学时不知道的领域寻求帮助
- javascript - 如何使用 jQuery 创建包含 Django 静态 src 的元素
- swift - RealmSwift:IndexPath 处的 MoveRow 出错了
- office-js - IOS Outlook应用程序中是否支持office js对话框api
- eclipse - Java 编辑器中的 Eclipse 禁用警告