java - How to modify a value to Tuple2 in Java
问题描述
I am using a accumulator within a fold function. I would like to change the value of the accumulator.
My function looks something like this:
public Tuple2<String, Long> fold(Tuple2<String, Long> acc, eventClass event)
{
acc._1 = event.getUser();
acc._2 += event.getOtherThing();
return acc
}
To me this should be working, because all I am doing is change the values of the accumulator. However what I get is Cannot assign value to final variable _1
. Same for _2
. Why are these properties of acc
final? How can I assign values to them?
quick edit:
Wat I could to is rust return a new Tuple instead, but this is not a nice solution in my opinion return new Tuple2<String, Long>(event.getUser(), acc._2 + event.getOtherThing());
solution for flink framework: Use the Tuple2 of defined in flink. Import it using
import org.apache.flink.api.java.tuple.Tuple2;
and then use it with
acc.f0 = event.getUser();
acc.f1 += event.getByteDiff();
return acc;
解决方案
I don't know what kind of Tuple2 you still use, but I assume it is a scala Tuple2. The scala Tuple2 it's immutable. You can't change the value of an Immutable object, you must to recreate it. Why? The scala Tuple2 is a functional programming "Data structure" so, as all concept of functional programming" it try to reduce side effect. You can use the .copy function to recreate it as you want. the following is an example of code:
@Test
public void test() {
Tuple2<String,Long> tuple = new Tuple2<>("a",1l);
Tuple2<String,Long> actual = tuple.copy(tuple._1,tuple._2+1);
Tuple2<String,Long> expected = new Tuple2<>("a",2l);
assertEquals(actual,expected);
}
推荐阅读
- python - 从对象数组中获取所有对象的特定属性的数组
- angular - 类型定义中的感叹号
- tensorflow - 如何在我的代码中使用张量核心而不是 cuda 核心?
- java - 在枚举中添加长方法是不好的设计吗?
- javascript - 调用 e.preventDefault() 后提交复选框表单
- html - 当显示设置为内联时,边距顶部不起作用
- javascript - 使用Router和Links在同一个地方渲染所有组件
- ruby - Savon ruby gem 的“dh 键太小”
- sql - 在 FK user_id 上为促销添加 UNIQUE 约束会阻止用户两次声称促销吗?
- spring-boot - 通过邮递员发送二维字节数组(多个文件)作为多部分请求