Search code examples
nattable

Adding custom comparator for integer sorting in Nattable


I tried sorting header layers, which is working fine for Text but not for Integers and dates - so I want to create a custom comparator for that.


Solution

  • First a comment on your issue. Sorting of Numbers and Dates is working pretty fine in NatTable. In fact the sorting of all Comparable data types is working fine with the DefaultComparator applied by the DefaultSortConfiguration. But to make it work correctly, you need to register the according data type converters as shown in various NatTable examples. Without the converter all data in NatTable is treated as String, which results in "incorrect" sorting.

    Second to your question. You can register a custom comparator like this:

    configRegistry.registerConfigAttribute(
        SortConfigAttributes.SORT_COMPARATOR,
        new MyCustomComparator(),
        DisplayMode.NORMAL,
        CUSTOM_COMPARATOR_LABEL);
    

    So you need to register a Comparator for the configuration attribute SortConfigAttributes.SORT_COMPARATOR and an according label.

    But if you do not have a matching type converter, you will need to compare Strings. So IMHO you need to register a DisplayConverter and sorting works as intended without the need for a custom comparator.