java - 需要帮助将 java.stream 转换为列表

标签 java list

我一生都无法理解如何转换此代码,我使用流为名为 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/

相关文章:

python - 通过 python 中的 lambda 函数拆分列表

java - 输出可由用户修改的数据驱动生成的图形

java - 如何在android中制作覆盖窗口?

java - Java中的维特比算法

java - android 应用程序在启动前崩溃

java - 使用 Java 8 流的复杂聚合

python - 如何在 python 中弹出子列表的内容?

c# - 对象列表,获取带有分隔符的属性

Python - 从txt文件导入列表,迭代并作为参数传递

java - 当再次处理相同的数据和任务时,Java 8 流是否会重用自身?