How can I sort an IntStream in ascending order?

2019-07-21 12:18发布

问题:

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