首页 > 解决方案 > 有没有可以合并两个排序数组的实用程序?

问题描述

我想知道是否有一些实用程序(库)可以在 1 行中合并两个排序数组。

标签: java

解决方案


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)

推荐阅读