Sort a list of Integers using a Collator

803 Views Asked by At

We're using the following simplified code snipped for sorting.

    Collator collator = Collator.getInstance(Locale.GERMAN);
    collator.setStrength(Collator.SECONDARY);
    return Comparator.comparing(entity -> {
        try {
            // Custom stuff here...
            // Values processed here cn be either String, Integer, Boolean or Date
            return (Comparable)sortFieldValue;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }, collator);

This is working fine for String values. However we'd like to reuse this to also compare Boolean, Integer, etc. With the given collator this results in:

java.lang.Integer cannot be cast to java.lang.String

When removing the collator sorting also works for ther data types than String but then e.g. German umlauts are not sorted as desired.

What could be an adequate way to "combine" using the collator for string-based values and ignoring it for other data types?

1

There are 1 best solutions below

0
Jakub Holý On

What we do is check the type of the entity being compared and only use the collator (via collator.compare(..)) if both values are actually strings.