Kar*_*ian 2 java mergesort iterable guava
我试图将几个列表合并为一个,消除重复.Guava中的mergeSorted方法似乎适用于我的情况.但是当我尝试它时,我看到有关我传递给方法的参数的编译错误.我的代码就像这样简单,我有两个列表,将它们连接成一个然后尝试mergeSort它,但我在第四行得到一个编译错误.
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 2, 5, 6);
Iterable<Integer> some = Iterables.concat(first, second);
final Iterable all = Iterables.<Integer>mergeSorted(some, comp);
System.out.println(all);
Run Code Online (Sandbox Code Playgroud)
看起来它是mergeSorted期待Iterable <?延伸Iterable <?扩展T >> iterables但方法描述似乎表明输入可以是所有给定iterables的合并内容
@Beta public static <T> Iterable <T> mergeSorted(Iterable <?extends Iterable <?extends T >> iterables,Comparator <?super T> comparator)
返回所有给定iterables的合并内容的可迭代.等效条目不会被重复数据删除.
调用者必须确保源迭代按非降序排列,因为此方法不对其输入进行排序.
Jon*_*eet 10
你目前正在合并之前将你的iterables连接在一起- 此时,除了其他任何东西之外,结果不再排序!
正如您所指出的,mergeSorted需要"可迭代的迭代".完整样本:
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class Test {
public static void main(String[] args) {
List<Integer> first = Lists.newArrayList(1, 2, 3);
// Note that each input list has to be sorted already!
List<Integer> second = Lists.newArrayList(2, 4, 5, 6);
Iterable<Integer> all = Iterables.mergeSorted(
ImmutableList.of(first, second), Ordering.natural());
System.out.println(Joiner.on(", ").join(all));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1478 次 |
| 最近记录: |