Build a Avro Schema with a list of field names and the same schema

at1ll3y :

im having a problem finding a solution for my problem.

I need to call the field method between the struct() and the build() method x times to create a new object. It's a builder pattern.

Schema people = SchemaBuilder.struct()
                .field("NAME", Schema.STRING_SCHEMA)
                .field("SURNAME", Schema.STRING_SCHEMA)
                .field("CITY", Schema.STRING_SCHEMA)
                .build();

But in my case, the fields of the people schema are not defined from the beginning. They need to be variable. I need something like:

String[] values = {"NAME", "SURNAME", "CITY", "FIELD4", "FIELD5", .....};

Schema people = SchemaBuilder.struct()
          .xTimes.field(values[x], Schema.STRING_SCHEMA))
          .build();

I looked at Streams and lambdas but never worked with them and am not sure if those could be a solution for this case. I can't interrupt the methods. They all need to be called in one row. Is what I'm trying to do even possible and if yes, how?

Thanks

EDIT: This is what I tried but didn't work:

public Schema buildSchema(String... fields){
  sch1 = SchemaBuilder.struct();
  for (int i = 0; i < fields.length; i++) {
    sch1 =SchemaBuilder.struct().field(fields[i], Schema.STRING_SCHEMA);
  }
  return sch1;
}

This works perfectly fine but doesn't fit my needs:

public Schema buildSchema(){
  Schema sch1 = SchemaBuilder.struct()
    .field("foo", Schema.STRING_SCHEMA)
    .field("bar", Schema.STRING_SCHEMA)
    .field("duck", Schema.STRING_SCHEMA)
    .build();
  return sch1
}
Shark :
String[] values = {"NAME", "SURNAME", "CITY", "FIELD4", "FIELD5", .....};

SchemaBuilder builder = SchemaBuilder.struct();
for (int i = 0; i < values.length; i++) {
    builder = builder.field(values[i], Schema.STRING_SCHEMA)
}
Schema people = builder.build();

how bout something like that?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=219297&siteId=1