【发布时间】:2016-10-26 06:30:47
【问题描述】:
我编写了一个合并函数,将两个排序列表合并为一个排序列表。以下是代码的场景。
- 合并列表 [2, 4, 6], [3, 5, 6, 7] 生成 [2, 3, 4, 5, 6, 6, 7]。
- 合并列表 [“Alice”、“Tom”]、[“Bob”、“Richard”] 生成 [“Alice”、“Bob”、“Richard”、“Tom”]。
- 合并列表 [2.3, 4.5], [2,5] 生成 [2, 2.3, 4.5, 5]。
-
合并列表 [“A”, “XYZ”, “AXTU”] 和 [2, 4, 6](其中第一个列表按字长排序,在合并操作中,如果字符串长度在第一个列表与第二个列表中的数字相同,字符串在前)产生 [“A”, 2, “XYZ”, “AXTU”, 4, 6];
public static void testCombine() { ArrayList<ArrayList<String>> mainList = new ArrayList<>(); ArrayList<String> list1 = new ArrayList<String>(Arrays.asList("Alice", "Tom")); ArrayList<String> list2 = new ArrayList<String>(Arrays.asList("Bob", "Richard")); mainList.add(list1); mainList.add(list2); System.out.println(combine(mainList.stream())); } private static <T extends Comparable<? super T>> ArrayList<T> combine(Stream<ArrayList<T>> stream) { return stream.reduce((x, y) -> { x.addAll(y); Collections.sort(x); return x; }).get(); }
但是,我没有得到 3 和 4 类型的结果。我必须实现最通用的合并功能,假设输入列表是有序的(根据自然或指定的顺序)
【问题讨论】:
-
为#4 提供自定义
Comparator到Collections.sort() -
当您的用户只想合并两个列表时,不要强迫他们创建流。您的 combine 方法应具有签名
static <T extends Comparable<T>, U extends Comparable<U>> List<Object> combine(List<T> tList, List<U> uList)。当 T 和 U 是 String 和 Integer 时使用自定义比较器。 -
另外,合并 sorted 列表的全部意义在于您不必再次对它们进行排序!