Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java stream collect function giving error

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>
like image 336
Curious Avatar asked Sep 26 '17 05:09

Curious


2 Answers

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.

like image 115
Joe C Avatar answered Nov 01 '22 07:11

Joe C


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();
like image 21
Eran Avatar answered Nov 01 '22 07:11

Eran