vaadinvaadin-grid

Sorting rows in a Grid column of String type based on corresponding integer values


I have the following structure for a Grid and wanted to know how to sort a column based on the Integer values of the Strings. The data provider is not flexible to change, so I have to sort with some kind of intermediary step:

Grid<String[]> grid = new Grid<>();
...

grid.addColumn(str -> str[columnIndex]).setHeader("sample").setKey("integercolumn").setSortable(true);

...

GridSortOrder<String> order = new GridSortOrder<>(grid.getColumnByKey("integercolumn"), SortDirection.DESCENDING);

grid.sort(Arrays.asList(order));

This sorts two digit numbers properly but not one digit or 3+.


Solution

  • You can define a custom comparator on the column that is used for sorting its values. In your case the comparator needs to extract the column-specific value from the array, and then convert it to an int:

            grid.addColumn(row -> row[columnIndex])
                    .setHeader("sample")
                    .setKey("integercolumn")
                    .setSortable(true)
                    .setComparator(row -> Integer.parseInt(row[columnIndex]));
    

    See https://vaadin.com/docs/latest/components/grid/#specifying-the-sort-property.