How can I sort an IntStream in ascending order?

南笙酒味 提交于 2019-12-24 05:42:33

问题


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.


回答1:


Try with

dataStream.sorted().boxed().collect(Collectors.toList());

because collect(Collectors.toList()) does not apply to a IntStream.

I also think that should be slightly better for performance call first sorted() and then boxed().

IntStream.collect() method has the following signature:

<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);

As suggested here:

How do I convert a Java 8 IntStream to a List?




回答2:


The problem is you're trying to convert an int stream to a list, but Collectors.toList only works on streams of objects, not streams of primitives.

You'll need to box the array before collecting it into the list:

dataStream.sorted().boxed().collect(Collectors.toList());



来源:https://stackoverflow.com/questions/44102620/how-can-i-sort-an-intstream-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!