Let's say I have a Message with a repeated field:
Message Foo {
repeated Bar bar = 1;
}
Now I want to insert n
Bar objects into the field bar, each is created in a loop.
for (i=0; i < n; i++){
//Add Bar into foo
}
//Build foo after loop
Is this possible or do I need all n
bar fields at the same time before building the foo Object?
Yes, repeated fields retain the order of items. From Google's Protocol Buffers encoding specification: The order of the elements with respect to each other is preserved when parsing, though the ordering with respect to other fields is lost.
repeated : this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
For Protobuf v2 You can use the DeleteSubrange(int start, int num) in RepeatedPtrField class. If you want to delete a single element then you have to call this method as DeleteSubrange(index_to_be_del, 1) . It will remove the element at that index.
gRPC services provide two ways of returning datasets, or lists of objects. The Protocol Buffers message specification uses the repeated keyword for declaring lists or arrays of messages within another message. The gRPC service specification uses the stream keyword to declare a long-running persistent connection.
When you use the protoc command to generate the java object it will create a Foo Object which will have its own builder method on it.
You will end up doing something like this
//Creates the builder object
Builder builder = Package.Foo.newBuilder();
//populate the repeated field.
builder.addAll(new ArrayList<Bar>());
//This should build out a Foo object
builder.build();
To add individual objects you can do something like this.
Bar bar = new Bar();
builder.addBar(bar);
builder.build();
Edited with the use case you've requested.
List<Bar> barList= new Arraylist();
barList.add(new Bar());
Then set the list of Bar in the Foo
Foo foo = Foo.newBuilder()
.addAllBar(barList)
.build;
You can set only one value for Bar
Foo foo = Foo.newBuilder()
.addBar(new Bar())
.build;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With