Reputation: 13476
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)));
}
I'm using Eclipse. The following error is given by eclipse.
Type mismatch: cannot convert from Stream<Object> to Stream<ProcessArray.Cell>
Upvotes: 1
Views: 1427
Reputation: 10291
Your Code maps to a Stream of Streams. Deviding it into declaration and return provides the following code:
Stream<Stream<Cell>> mapToObj = IntStream.range(0, rows).mapToObj(row -> IntStream.range(0, cols).mapToObj(col -> new Cell(row, col)));
return mapToObj;
You need to reduce your Streams to a single Stream:
// 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);
Edit: As pointed out by Holger in the comments, reducing a Stream of Streams with Stream.concat() is not very performant. Use one of the other solutions utilizing the flatMap
method instead of reduce
.
Upvotes: 1
Reputation: 13476
An alternative solution to @flo's
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)));
}
Upvotes: 3
Reputation: 4579
@flo's answer, reworked to use flatMap instead (flatMap "embeds" the Stream returned by the flatMapping function into the original 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
;
Upvotes: 1