Sort incorrect behavior in Grid with custom comparator on reversed order

Hello,
In Grid component, when you set a custom comparator on a column, I expect the reversed() method of my comparator to be used when I select reversed order in the header.
However, the reversed order is generated by inverting the ascending order of my comparator, not by using the reversed method.
Digging into the code, we can see that int the class Column (Vaadin 24.8.8):

public Column<T> setComparator(Comparator<T> comparator) {
            Objects.requireNonNull(comparator, "Comparator must not be null");
            this.setSortable(true);
            this.comparator = comparator::compare;
            return this;
        }

Knowing that this.comparator is an instance of SerializableComparator, an internal class, the line this.comparator = comparator::compare; create a new instance of SerializableComparator based on the compare(T,T) method of the given comparator (here my custom comparator).
This prevents the method reversed() to be used in the subsequent uses of this.comparator.
Specially in:

  public SerializableComparator<T> getComparator(SortDirection sortDirection) {
            Objects.requireNonNull(comparator, "No comparator defined for sorted column.");
            setSortable(true);
            boolean reverse = sortDirection != SortDirection.ASCENDING;
            return reverse ? comparator.reversed()::compare : comparator;
        }

I would like to use my reversed method instead of the built-in one.

I’m curious about why you want this. Does it mean that you want the reversed order to not actually be the opposite of the regular order?

Anyways, it looks like adding support for this would require a relatively small code change to the Grid implementation. If you’re interested, then a Pull Request would be appreciated.

Hi Leif,
Thanks for your answer.
I think it’s quite a common case, for instance I have a column with dates and some of them can be null. I want to always place the null values at the end whether the sort is ascending or descending.

I added a request here: Sort incomplete behavior in Grid with custom comparator on reversed order · Issue #8075 · vaadin/platform · GitHub

Why don’t you sort in the database ?

Some reasons I’ve had in the past:

For a simple in-memory Grid with not so many rows, using the lazy loading is overkill sometimes.

Some of my Comparator are so special that they can’t be done on DB level (don’t ask… germans have their way of making things complicated)

NullsFirst/NullsLast is not available in “earlier” JPA Versions

I use jOOQ and everything is possible with SQL :wink:

1 Like

There is no underlying database.