First statement works but not second giving below error, why ?
java.util.Arrays.asList(1,2,3,4,5).stream()
.map(n -> n+1)
.collect(Collectors.toList());
List<Integer> list = IntStream.rangeClosed(1, 10)
.map(n -> n + 1)
.collect(Collectors.toList());
ERROR:
Type mismatch: cannot convert from Collector<Object,capture#5-of ?,List<Object>>
to Supplier<R>
While there is a collect method on a Stream which accepts a Collector, there is no such method on an IntStream.
You can convert your IntStream to a Stream<Integer> using the boxed() method.
The first statement produces a Stream<Integer> which has a collect method that takes a Collector.
The second statement produces an IntStream which does not have a collect method.
In order for the second statement to work,
you must convert the IntStream to a Stream<Integer> as follows:
List<Integer> list = IntStream.rangeClosed(1, 10)
.map(n -> n + 1)
.boxed()
.collect(Collectors.toList());
or you can produce an int array instead of a List<Integer>:
int[] array = IntStream.rangeClosed(1, 10)
.map(n -> n + 1)
.toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With