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

时间:2018-06-05 06:35:23

标签: java list

我无法理解如何转换此代码,我使用了流来为CARDINAL_NEIGHBORS创建一个列表。但是我的教授决定改变签名,而不是允许我们使用我们不能使用的流。我已经尝试使用函数和lambda组合构建一个列表,但它似乎没有用,任何人都可以帮我解决这个问题吗?我需要将常量CARDINAL_NEIGHBORS传递给一个用于AStar路径策略的computepath方法......

所以这就是我原来的......

    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);
      }

2 个答案:

答案 0 :(得分:4)

使用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())

答案 1 :(得分:1)

不需要流也可以像这样使用lambda。

static final Function<Point, List<Point>> CARDINAL_NEIGHBORS =
  point ->
  {
    List<Point> list = new ArrayList<>();
    list.add(new Point(point.x, point.y - 1));
    list.add(new Point(point.x, point.y + 1));
    list.add(new Point(point.x - 1, point.y));
    list.add(new Point(point.x + 1, point.y));
    return list;
  };