public static Stream<Cell> streamCells(int rows, int cols) {
return IntStream.range(0, rows).mapToObj(row -> IntStream.range(0, cols).mapToObj(col -> new Cell(row, col)));
}我在用Eclipse。eclipse给出了以下错误。
Type mismatch: cannot convert from Stream<Object> to Stream<ProcessArray.Cell>发布于 2015-01-28 06:43:32
@flo的另一种解决方案
public static Stream<Cell> streamCells(int rows, int cols) {
return IntStream.range(0, rows).boxed()
.flatMap(row -> IntStream.range(0, cols).mapToObj(col -> new Cell(row, col)));
}发布于 2015-01-28 05:56:07
您的代码映射到流。将其划分为声明和返回提供了以下代码:
Stream<Stream<Cell>> mapToObj = IntStream.range(0, rows).mapToObj(row -> IntStream.range(0, cols).mapToObj(col -> new Cell(row, col)));
return mapToObj;您需要将您的流缩减为单个流:
// CAVE: poor performance
return IntStream.range(0, rows)
.mapToObj(row -> IntStream.range(0, cols).mapToObj(col -> new Cell(row, col)))
.reduce(Stream.empty(), Stream::concat); 编辑:正如霍格在评论中指出的那样,用Stream.concat()减少流不是很好的表现。使用其他解决方案之一,使用flatMap方法而不是reduce。
发布于 2015-01-28 06:23:25
@flo的答案,改为使用flatMap (flatMap将flatMapping函数返回的流“嵌入”到原始流中):
return IntStream.range(0, rows)
.mapToObj(row -> IntStream.range(0, cols)
.mapToObj(col -> new Cell(row, col))
) // int -> Stream<Cell>
.flatmap(Function.identity()) // Stream<Cell> -> Cell
;https://stackoverflow.com/questions/28185310
复制相似问题