如何在 Java 中将值修改为 Tuple2

我在折叠函数中使用累加器。我想更改累加器的值。


我的函数看起来像这样:


public Tuple2<String, Long> fold(Tuple2<String, Long> acc, eventClass event) 

{

    acc._1 = event.getUser();

    acc._2 += event.getOtherThing();

    return acc

}

对我来说这应该是可行的,因为我所做的就是改变累加器的值。但是我得到的是Cannot assign value to final variable _1. 对_2. 为什么这些属性是accfinal的?如何为它们分配值?


快速编辑: Wat I can to be rust return a new Tuple,但在我看来这不是一个好的解决方案return new Tuple2<String, Long>(event.getUser(), acc._2 + event.getOtherThing());


flink框架的解决方案: 使用flink中定义的Tuple2。使用导入它


import org.apache.flink.api.java.tuple.Tuple2;

然后将其与


acc.f0 = event.getUser();

acc.f1 += event.getByteDiff();

return acc;


慕工程0101907
浏览 781回答 2
2回答

白板的微信

我不知道你还在使用哪种 Tuple2,但我认为它是一个 scala Tuple2。scala Tuple2 它是不可变的。您无法更改 Immutable 对象的值,您必须重新创建它。为什么?scala Tuple2 是一个函数式编程“数据结构”,因此,作为“函数式编程”的所有概念,它试图减少副作用。您可以使用 .copy 函数根据需要重新创建它。以下是代码示例:&nbsp;@Test&nbsp; &nbsp; public void test() {&nbsp; &nbsp; &nbsp; &nbsp; Tuple2<String,Long> tuple = new Tuple2<>("a",1l);&nbsp; &nbsp; &nbsp; &nbsp; Tuple2<String,Long> actual = tuple.copy(tuple._1,tuple._2+1);&nbsp; &nbsp; &nbsp; &nbsp; Tuple2<String,Long> expected = new Tuple2<>("a",2l);&nbsp; &nbsp; &nbsp; &nbsp; assertEquals(actual,expected);&nbsp; &nbsp; }

阿晨1998

我不知道Tuple2你在和哪个合作。如何返回一个新对象:Tuple2<String, Long> tuple = new Tuple2<String, Long>();tuple._1 = event.getUser();tuple._2 = event.getOtherThing() + acc._2;return tuple;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java