Milan Panic
Milan Panic

Reputation: 503

Lombok builder, build half of the object, then finish building the other half

I have a class:

@Builder
public class Foo {
   private String id;
   private String a;
   private String b;
}

I want to build an object with some restrictions. I want all the objects built to have a value a, but I want to make a check, and only if the object's id is in a List, I want to build it's 'b' value.

...

for(Foo foo: foos) {
   Foo.FooBuilder builder = Foo.builder();
   builder.a("bar1");

   if(listOfIds.contains(foo.getId)) {
      builder.b("bar2");
   }
   foo = builder.build();
}
...

That is an example of my code. So, I'm asking if this is the correct way to do it with the builder, or is there a better way to do this using builder.

Upvotes: 1

Views: 1079

Answers (1)

Tran Ho
Tran Ho

Reputation: 1500

UPDATED

In case you want to modify every element in the list. You can try this code:

for(int i = 0; i < foos.size();i++) {
  Foo.FooBuilder builder = Foo.builder();
  builder.a("bar1");

  if(listOfIds.contains(foo.getId())) {
  builder.b("bar2");
  //TODO: copy other values from `foos.get(i)` to builder. It's your turn
  //update modified to the list at i
  foos.set(i, builder.build());   
}

}

=========================

Assume that foo is a Foo object. Then your code will not be compiled. You just need to set property a of the builder like my code. After setting all the properties in the Foo builder, run builder.build() to get your foo.

Foo.FooBuilder builder = Foo.builder();

for(Foo foo: foos) {
  builder.a("bar1");

  if(listOfIds.contains(foo.getId())) {
    builder.b("bar2");
  }

  foo = builder.build();

}

Upvotes: 3

Related Questions