Vaadin - adding columns to grid from map

519 Views Asked by At

I want to show data in vaadin's grid, but I want to create columns dynamically for each value from customAttributes list. My data model more or less look like this

Item
    name: String
    localization: Localization
    visible: Boolean
    customAttributes: List<CustomAttribute>

CustomAttribute
    name: String
    value: String

Each Item has the same set of attribute types, only the values are different. User can manually defined new attribute types.

How can I create this grid? Currently I do it in this way:

grid.setColumns("name", "visible");
grid.addColumn(v -> v.getLocalization().getName()).setHeader("Localization");

But I have no idea for dynamic creating columns for each custom attribute.

1

There are 1 best solutions below

0
On BEST ANSWER

Like it was already written in the comments, you can loop over the attribute names assuming your have a list (or set) of them. One small gotcha is that you need to do that in a way that ensures values inside the callback are effectively final.

attributeNames.forEach(name -> {
  grid.addColumn(item -> item.getCustomAttributes().get(name))
    .setHeader(name);
});

If you don't directly know the attribute names but you're loading all items into memory instead of lazy loading them, then you can find the unique names by iterating over all items:

items.stream().flatMap(item -> item.getCustomAttributes().keySet().stream())
  .distinct().forEach(<same loop as in the previous example>);