Java TreeSet create with custom comparator using lambda expression

Introduction

We can create TreeSet with custom comparator using lambda expression in Java.

//lambda expression
TreeSet<String> ts = new TreeSet<String>((aStr, bStr) -> bStr.compareTo(aStr));

vs

// A reverse comparator for strings.  
class MyComp implements Comparator<String> {  
  public int compare(String aStr, String bStr) {  
  
    // Reverse the comparison. 
    return bStr.compareTo(aStr);  
  }  //w ww  .  j a v  a  2s  . co m
  
  // 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.TreeSet;

public class Main {
  public static void main(String args[]) {
    TreeSet<String> ts = new TreeSet<String>((aStr, bStr) -> bStr.compareTo(aStr));
    // 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();//from   ww w  . j a v  a2  s .  co  m
  }
}



PreviousNext

Related