Java TreeSet create with custom comparator

Introduction

We can create TreeSet with custom comparator in Java.

// A reverse comparator for strings.  
class MyComp implements Comparator<String> {  
  public int compare(String aStr, String bStr) {  
  
    // Reverse the comparison. 
    return bStr.compareTo(aStr);  
  }  /*from  w  w w . ja v a2s  .c  om*/
  
  // No need to override equals or the default methods.  
}  
TreeSet<String> ts = new TreeSet<String>(new MyComp()); 

Full source


// Use a custom comparator.  
import java.util.*;  
  
// A reverse comparator for strings.  
class MyComp implements Comparator<String> {  
  public int compare(String aStr, String bStr) {  
    // Reverse the comparison. 
    return bStr.compareTo(aStr);  
  }  //from w  ww .  j a v  a 2s  . co m
  
  // No need to override equals or the default methods.  
}  
  
public class Main {  
  public static void main(String args[]) {  
    // Create a tree set. 
    TreeSet<String> ts = new TreeSet<String>(new MyComp());  
      
    // Add elements to the tree set. 
    ts.add("HTML");  
    ts.add("CSS");  
    ts.add("demo2s.com");  
    ts.add("Java");  
    ts.add("Javascript");  
    ts.add("Dart");  
  
    // Display the elements. 
    for(String element : ts) 
      System.out.print(element + " ");  
 
    System.out.println();  
  }  
}



PreviousNext

Related