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