2017-09-26 85 views
3

第一条语句有效,但不是第二条给出的错误,为什么?java流收集函数给出错误

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> 
+2

因为'IntStream'是一个原始'int'值的流,而不是'整数'值。 – Andreas

回答

6

虽然Stream接受Collector的方法有collect,但上没有这种方法。

您可以使用boxed()方法将IntStream转换为Stream<Integer>

6

第一语句产生一个Stream<Integer>具有collect方法,它接受Collector

第二条语句产生一个IntStream,它没有collect方法。

为了给第二条语句的工作, 必须将IntStream转换为Stream<Integer>如下:

List<Integer> list = IntStream.rangeClosed(1, 10) 
           .map(n -> n + 1) 
           .boxed() 
           .collect(Collectors.toList()); 

,或者您可以产生int阵列,而不是一个List<Integer>

int[] array = IntStream.rangeClosed(1, 10) 
         .map(n -> n + 1) 
         .toArray(); 
+5

您也可以使用'mapToObj'而不是'map(...).boxed()'。 – Holger