【问题标题】:Updating collection items in Java在 Java 中更新集合项
【发布时间】:2019-01-20 15:17:03
【问题描述】:

我正在尝试根据条件对集合项目进行部分更新。这是Java代码sn-p:

public class Point {
    public int x = 0;
    public int y = 0;

    public Point(int a, int b) {
        x = a;
        y = b;
    }

    public String toString() {
      return this.x + ":" + this.y;
    }
}


public class HelloWorld
{

  public static void main(String[] args)
  {
    Point p1 = new Point(1, 1);
    Point p2 = new Point(2, 2);

    Collection<Point> arr = new ArrayList<Point>();
    arr.add(p1);
    arr.add(p2);

    arr.stream().map(el -> el.x == 2 ? el.y : 20);

    System.out.println(Arrays.toString(arr.toArray()));
  }
}

如您所见,此函数返回:[1:1, 2:2],但我想要的是:[1:1, 2:20]

我相信集合是不可变的,这就是我无法就地修改对象的原因。我的实际代码是 ElasticSearch 中的无痛脚本:

ctx._source.points = ctx._source.points
    .stream()
    .map(point -> point.x == 2 ? point.y : 20);
    .collect(Collectors.toList())

我相信这会转化为上面的 Java 代码。

我在 Java 方面没有太多经验。这就是为什么我无法弄清楚哪种数据结构可以让我在 Java 中改变可以在 ElasticSearch 无痛脚本语言中使用的列表元素。

【问题讨论】:

    标签: java list elasticsearch replace elasticsearch-painless


    【解决方案1】:

    您没有执行任何试图更改arr 内容的操作。您创建其元素的流,然后将其映射到整数流,但随后您不会对流执行任何操作。

    你可能想做这样的事情:

    arr.stream().filter(p -&gt; p.x == 2).forEach(p -&gt; p.y = 20);

    【讨论】:

      【解决方案2】:

      如果你想修改你的收藏,你可能需要这个

      arr = arr.stream()
                  .map(point -> point.x == 2 ? new Point(point.x, 20) : point)
                  .collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多