Search code examples
javasyntaxprotocol-buffers

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


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
}

Solution

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

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