Java – 如何将值列表分配给重复的protobuf字段而不使用for循环?

huangapple go评论70阅读模式
英文:

Java - How to assign a list of values to a repeated protobuf field without for loop?

问题

以下是翻译的内容:

假设TextDataTextDataFields是两个protobuf消息,但TextDataFields也是在TextData中交错出现的一个重复字段^1

这段代码目前可以编译:

request.getTextData(0)
       .toBuilder()
       .setTextDataFields(0, request.getTextDataFields(0))
       .build()

然而,在第3行,由于TextDataFields是重复的,可能有多个或零个值。目前的代码只获取第一个TextDataFields值,忽略其余的(如果没有,会导致索引越界错误)。

我的问题是,如何修改第3行以捕获所有的TextDataFields?所以它会类似于:

request.getTextData(0)
       .toBuilder()
       .setTextDataFields(i, request.getTextDataFields(i) for i in range(0, request.getTextDataFieldsCount)))
       .build()

也许可以使用stream()intstream()吗?

谢谢!


message TextData {
  optional string id = 1;
  repeated TextDataField text_data_fields = 2;
}

message TextDataField {
  optional string id = 1;
  ... # 其他字段
}
英文:

Suppose TextData and TextDataFields are two protobuf messages, but TextDataFields is also a repeated field interleaved in TextData^1

This current code can compile:

request.getTextData(0)
       .toBuilder()
       .setTextDataFields(0, request.getTextDataFields(0))
       .build()

However, on the 3rd line, since TextDataFields is repeated, there can be more than one or zero values. Currently the code only gets the first TextDataFields value and ignores the rest (And if there's none, it would have an index out of bound error)

My question is, how to modify the 3rd line to capture all the TextDataFields? So it would be something like

request.getTextData(0)
       .toBuilder()
       .setTextDataFields(i, request.getTextDataFields(i) for i in range(0, request.getTextDataFieldsCount)))
       .build()

Maybe use stream() or intstream()?

Thanks!


^1: An example would be like:

message TextData {
  optional string id = 1;
  repeated TextDataField text_data_fields = 2;
}

message TextDataField {
  optional string id = 1
  ... # other fields
}

答案1

得分: 0

我可以使用Protobuf中的“add all”功能,如下所示:

request.getTextData(0)
       .toBuilder()
       .addAllTextDataFields(request.getTextDataFieldsList())
       .build()
英文:

As it turned out, I can simply use the "add all" function from Protobuf

request.getTextData(0)
       .toBuilder()
       .addAllTextDataFields(request.getTextDataFieldsList())
       .build()

huangapple
  • 本文由 发表于 2023年2月16日 15:50:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定