简体   繁体   中英

How can I sort an IntStream in ascending order?

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM