23

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?

0

2 Answers 2

36

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.

3
  • Yes this is what i do now, but i was hoping to find something where i can insert the inner objects one by one.
    – Gobliins
    Commented Mar 20, 2015 at 15:40
  • edited the message, there should be an option to pass in the individual objects one by one as well.
    – Venki
    Commented Mar 20, 2015 at 15:47
  • How does one do this with a one-liner?
    – silvalli
    Commented Feb 29, 2020 at 23:28
5
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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.