2

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 */);
mslowiak
  • 1,688
  • 12
  • 25
  • Possible duplicate of [Reverse a comparator in Java 8](https://stackoverflow.com/questions/32995559/reverse-a-comparator-in-java-8) – kryger Oct 26 '17 at 08:08

2 Answers2

4

Just reverse the CASE_INSENSITIVE_ORDER comparator:

Set<String> caseInsensitiveStrings =
    new TreeSet<>(String.CASE_INSENSITIVE_ORDER.reversed());
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
Set<String> caseInsensitiveStrings = new TreeSet<String>(new Comparator<String>(){
    @Override
    public int compare(String o1, String o2) {
       // throw new UnsupportedOperationException("Not supported yet.");
        if(o1.equalsIgnoreCase(o2)){
            return 0;
        }else if(o1.compareTo(o2)== 1){
             return -1;
        }else if(o1.compareTo(o2)== -1){ 
             return 1;
        } 
        return o1.compareTo(o2);
    }
 });
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
jai
  • 98
  • 8