Search code examples
javacomparatorcase-insensitivetreeset

Sort list with two specifications


I would like to sort a TreeSet with two criteria.

Collections.reverseOrder() and String.CASE_INSENSITIVE_ORDER

I know that I can make it with single of them:

Set<String> set1 = new TreeSet<>(Collections.reverseOrder());
Set<String> set2 = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);

How should I implement a comparator to get this two criteria in one tree set?

Set<String> ser3 = new TreeSet<>(/* here comparator */);

Solution

  • Just reverse the CASE_INSENSITIVE_ORDER comparator:

    Set<String> caseInsensitiveStrings =
        new TreeSet<>(String.CASE_INSENSITIVE_ORDER.reversed());