假设我们有一个算法在循环中顺序生成项目(每次迭代一个项目),我们希望将此算法放入一个返回这些项目流的方法中.
哪种方法最好; 这个?
Stream<Cell> streamCellsTouchingRay(Point2D fromPoint, Vector2D direction){
// ...
Stream<Cell> stream = Stream.of(/* 1st item */);
while(/* ... */){
// ...
stream = Stream.concat(stream, /* i'th item */);
}
}
Run Code Online (Sandbox Code Playgroud)
......还是这个?
Stream<Cell> streamCellsTouchingRay(Point2D fromPoint, Vector2D direction){
// ...
ArrayList<Cell> cells = new ArrayList<>(/* required capacity is known */);
cells.add(/* 1st item */);
while(/* ... */){
// ...
cells.add(/* i'th item */);
}
return cells.stream();
}
Run Code Online (Sandbox Code Playgroud)
......还是其他方法呢?
完全另一种方法:使用Stream.Builder.
Stream<Cell> streamCellsTouchingRay(Point2D fromPoint, Vector2D direction){
// ...
Stream.Builder<Cell> cells = Stream.builder();
cells.add(/* 1st item */);
while(/* ... */){
// ...
cells.add(/* i'th item */);
}
return cells.build();
}
Run Code Online (Sandbox Code Playgroud)