首页 > 解决方案 > 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;

标签: javascalaapache-flinkfinalaccumulator

解决方案


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);
    }


推荐阅读