如何按升序对IntStream进行排序? [英] How can I sort an IntStream in ascending order?
本文介绍了如何按升序对IntStream进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将2D int数组转换为Stream:
I've converted a 2D int array into a Stream:
IntStream dataStream = Arrays.stream(data).flatMapToInt(x -> Arrays.stream(x));
现在,我想按升序对列表进行排序。我试过这个:
Now, I want to sort the list into ascending order. I've tried this:
dataStream.sorted().collect(Collectors.toList());
但我收到编译时错误
but I get the compile time error
我对此感到困惑,因为在我看过的例子中,类似的事情没有错误。
I'm confused about this, because on the examples I've seen, similar things are done without errors.
推荐答案
尝试
dataStream.sorted().boxed().collect(Collectors.toList());
因为 collect(Collectors.toList())
不适用于 IntStream
。
我还认为性能调优应该稍好一些 sorted()
然后 boxed()
。
I also think that should be slightly better for performance call first sorted()
and then boxed()
.
IntStream.collect()
方法具有以下签名:
<R> R collect(Supplier<R> supplier,
ObjIntConsumer<R> accumulator,
BiConsumer<R, R> combiner);
如果你真的想要使用它你可以:
If you really want use this you could:
.collect(IntArrayList::new, MutableIntList::add, MutableIntList::addAll);
如此处所示:
这篇关于如何按升序对IntStream进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文