gpt4 book ai didi

java - 二维坐标上的流/IntRange?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:47 24 4
gpt4 key购买 nike

我有以下类(class):

public class Rectangle
{
public int width, height;
public Point start;

public Rectangle(Point start, int width, int height)
{
this.start = start;
this.width = width;
this.height = height;
}
}

public class Point
{
public int x, y;

public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}

我想创建一个 Rectangle 类的方法,以便返回类型为 Point 的 Java 8 Stream,它将流式传输矩形内的索引位置。前任。

// This is inside the rectangle class.
public Stream<Point> stream(int hstep, int vstep)
{
// if the rectangle started at 0,0
// and had a width and height of 100
// and hstep and vstep were both 1
// then the returned stream would be
// 0,0 -> 1,0 -> 2,0 -> ... -> 100,0 -> 0,1 -> 1,1 -> ...

// If vstep was 5 and h step was 25 it would return
// 0,0 -> 25,0 -> 50,0 -> 75,0 -> 100,0 -> 0,5 -> 25,5 -> ...

return ...
}

我经常使用 IntStreammapfilter 等,但这比我尝试过的任何东西都复杂得多.我不知道我会怎么做那样的事情。有人可以引导我走向正确的方向吗?

最佳答案

您可以使用嵌套的 IntStream 生成每个 Point,然后展平生成的流:

public Stream<Point> stream(int hstep, int vstep) {
return IntStream.range(0, height / vstep)
.mapToObj(y -> IntStream.range(0, width / hstep)
.mapToObj(x -> new Point(start.x + x * hstep, start.y + y * vstep)))
.flatMap(Function.identity());
}

关于java - 二维坐标上的流/IntRange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com