2017-09-26 9 views
3

最初のステートメントは動作しますが、2番目のエラーは以下の理由で発生します。なぜですか?エラーを返す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値のストリームであり、ボックス化されたInteger値ではないためです。 – Andreas

答えて

6

Collectorを受け入れるStreamにはcollectメソッドがありますが、そのようなメソッドはありません。。

boxed()メソッドを使用してIntStreamStream<Integer>に変換できます。

6

最初の文はCollectorを取るcollect方法を持っているStream<Integer>を生成します。

collectメソッドを持たないIntStreamが生成されます。第二文が動作するためには

、 次のようにStream<Integer>IntStreamを変換する必要があります。

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

またはあなたの代わりにList<Integer>int配列を生成することができた:

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

'map(...).boxed()'の代わりに 'mapToObj'を使うこともできます。 – Holger

関連する問題