英文:
Java - How to assign a list of values to a repeated protobuf field without for loop?
问题
以下是翻译的内容:
假设TextData
和TextDataFields
是两个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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论