为什么这个 java 8 代码不能编译?
Why won't this java 8 code compile?
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>
您的代码映射到流中的流。将其分解为声明和 return 提供以下代码:
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);
编辑: 正如 Holger 在评论中指出的那样,使用 Stream.concat() 减少 Stream of Streams 的性能不是很好。使用 flatMap
方法代替 reduce
.
的其他解决方案之一
@flo 的回答,修改为使用 flatMap(flatMap "embeds" flatMapping 函数返回的 Stream 到原始流中):
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
;
@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)));
}
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>
您的代码映射到流中的流。将其分解为声明和 return 提供以下代码:
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);
编辑: 正如 Holger 在评论中指出的那样,使用 Stream.concat() 减少 Stream of Streams 的性能不是很好。使用 flatMap
方法代替 reduce
.
@flo 的回答,修改为使用 flatMap(flatMap "embeds" flatMapping 函数返回的 Stream 到原始流中):
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
;
@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)));
}