Search code examples
javavaadinvaadin8vaadin-grid

How do you setup a Grid in Vaadin 8 to sort by a custom comparator?


So for example my grid is composed of People so that I have:

public class People
{
    int id;
    String name;
}

My grid is such that I have:

grid.addColumn(People::getName).setId("Name");

Now I know I can do:

grid.sort("Name", SortDirection.ASCENDING);

The problem is what if I have two people with the same name, say John. In this case I want to first sort by name and then by id. The id is not a column in the grid, it's just a property of the People class.

Although this example is oversimplified I do include additional information so it's important that I'm able to sort by the actual person and not just the name. In my case the grid is a report and the person's name is just one of many fields.


Solution

  • The way I ended up doing it, assuming you have a list of Cars with People being one of the columns, is:

    Grid<Car> grid = new Grid<Car>();
    grid.addColumn(Car::getPerson).setComparator((car1, car2) -> 
    {
        // ignoring any null checks for getPerson() as they can be null.
        return car1.getPerson().compareTo(car2.getPerson());               
    });