【问题标题】:How to return a list with all the points made with the xs and the ys. when using streams in java? [duplicate]如何返回包含 xs 和 ys 的所有点的列表。在java中使用流时? [复制]
【发布时间】:2021-08-23 07:17:09
【问题描述】:
  • 不应包含重复点;即具有相同坐标的点。
  • 并且不应包含负坐标的点。

这是我到目前为止所得到的,但我正在努力对 y 坐标做同样的事情。

static List<Point> ex5(List<Integer>xs, List<Integer> ys){
    List<Point> p = xs.stream()
            .map(e -> new Point(e , 0))
            .collect(Collectors.toList());
    return p ;
}

以下是示例数据。知道我在这里缺少什么吗?

List<Integer> pointx = new ArrayList<>();
pointx.add(1);
pointx.add(-2);
pointx.add(3);
pointx.add(4);
pointx.add(1);

List<Integer> pointy = new ArrayList<>();
pointy.add(6);
pointy.add(7);
pointy.add(8);
pointy.add(9);
pointy.add(6);

【问题讨论】:

  • 能否在您的问题中添加预期的输出。实际上不清楚你的意思是努力用y坐标做“同样的事情”
  • 尝试在重复链接中寻找方法,然后尝试构建您的确切解决方案。

标签: java java-stream


【解决方案1】:

从两个原始列表的索引IntStream 开始。这将允许您处理每个列表中的数字对。

static List<Point> ex5(List<Integer>xs, List<Integer> ys){
    if (xs.size() != ys.size()) {
        throw new IllegalArgumentException("Must have smae size");
    }
    List<Point> p = IntStream.range(0, xs.size())
            .filter(index -> xs.get(index) >= 0 && ys.get(index) >= 0)
            .mapToObj(index -> new Point(xs.get(index), ys.get(index)))
            .distinct()
            .collect(Collectors.toList());
    return p ;
}

distinct 操作删除重复项。还有不紧跟的重复,我不确定你是否想要那个。

【讨论】:

  • 你真的要给xs.get(..)打两次电话吗?
  • @NikolasCharalambidis 不是真的。这有点快,我鼓励任何使用我的代码的人进行他们喜欢的任何调整。您可以交换过滤和点对象的创建。然后,您甚至可以为 Point 类配备 hasNonnegativeCoords 过滤方法。
  • 谢谢帮助:)
【解决方案2】:

它不应包含重复的点;即具有相同坐标的点。

正确实施equalshashCode。使用Stream#distinct() 方法或Set 而不是List

它不应该包含负坐标的点。

使用Stream#filter(Predicate) 过滤掉不需要的值。


static List<Point> ex5(List<Integer> xs, List<Integer> ys){
    Set<Point> set = new HashSet<>();
    int min = Math.min(xs.size(), ys.size());
    for (int i=0; i<min; i++){
        int x = xs.get(i);
        int y = ys.get(i);
        if (x >=0 && y>=0) {
            set.add(new Point(x, y));
        }
    }
    return new ArrayList<>(set);
}

几点说明:

  • 我使用Math#min(int, int) 来避免IndexOutOfBoundsException。您可能希望以更好的方式处理列表大小不相等的情况。

  • 使用IntStream#ange(int, int) 可以使用,但它没有带来真正的好处。对于某些开发人员来说,它可能看起来更具可读性(个人喜好问题)。

    int min = Math.min(xs.size(), ys.size());
    Set<Point> set = IntStream.range(0, min)
            .mapToObj(i -> new Point(xs.get(i), ys.get(i)))
            .filter(point-> point.getX()>=0 && point.getY()>=0)
            .collect(Collectors.toSet());
    return new ArrayList<>(set);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2018-03-02
    • 2014-06-17
    相关资源
    最近更新 更多