我正在尝试根据条件对集合项目进行部分更新。下面是 Java 代码片段:
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 无痛脚本语言中使用。
最佳答案
您没有执行任何尝试更改 arr
内容的操作。您创建其元素的流,然后将其映射到整数流,但随后不对该流执行任何操作。
您可能想做类似的事情:
arr.stream().filter(p -> p.x == 2).forEach(p -> p.y = 20);
关于java - 在 Java 中更新集合项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51830003/