我一生都无法理解如何转换此代码,我使用流为名为 CARDINAL_NEIGHBORS 的东西构建了一个列表。但是我的教授决定更改签名,而不是允许我们使用我们不能使用的流。我尝试过使用函数和 lambda 组合构建列表,但它似乎不起作用,任何人都可以帮助我解决这个问题吗?我需要将常量 CARDINAL_NEIGHBORS 传递给 AStar 路径策略的计算路径方法...
这就是我最初拥有的......
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
interface PathingStrategy
{
/*
* Returns a prefix of a path from the start point to a point within reach
* of the end point. This path is only valid ("clear") when returned, but
* may be invalidated by movement of other entities.
*
* The prefix includes neither the start point nor the end point.
*/
List<Point> computePath(Point start, Point end,
Predicate<Point> canPassThrough,
Function<Point, Stream<Point>> potentialNeighbors);
static final Function<Point, Stream<Point>> CARDINAL_NEIGHBORS =
point ->
Stream.<Point>builder()
.add(new Point(point.x, point.y - 1))
.add(new Point(point.x, point.y + 1))
.add(new Point(point.x - 1, point.y))
.add(new Point(point.x + 1, point.y))
.build();
}
///-------------------------------------------------------- ---------------------------------
这就是我现在需要的......
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
interface PathingStrategy {
/*
* Returns a prefix of a path from the start point to a point within reach
* of the end point. This path is only valid ("clear") when returned, but
* may be invalidated by movement of other entities.
*
* The prefix includes neither the start point nor the end point.
*/
List<Point> computePath(Point start, Point end,
Predicate<Point> canPassThrough,
Function<Point, List<Point>> potentialNeighbors);
}
最佳答案
使用Collectors.toList
将流的内容收集到列表中。
point -> Stream.<Point>builder()
.add(new Point(point.x, point.y - 1))
.add(new Point(point.x, point.y + 1))
.add(new Point(point.x - 1, point.y))
.add(new Point(point.x + 1, point.y))
.build()
.collect(Collectors.toList());
以上返回Function<Point, List<Point>>
您还可以使用Stream.of(...).collect(Collectors.toList())
关于java - 需要帮助将 java.stream 转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50693542/