Java Collection How to - Add objects to Binary Search tree using custom comparator








Question

We would like to know how to add objects to Binary Search tree using custom comparator.

Answer

import java.util.Comparator;
import java.util.TreeSet;
// w w  w  .j  a va 2s  .com
public class Main {
  public static void main(String a[]) {
    // By using name comparator (String comparison)
    TreeSet<Empl> nameComp = new TreeSet<Empl>(new MyNameComp());
    nameComp.add(new Empl("R", 3));
    nameComp.add(new Empl("J", 6));
    nameComp.add(new Empl("C", 20));
    nameComp.add(new Empl("T", 2));

    System.out.println(nameComp);

    // By using salary comparator (int comparison)
    TreeSet<Empl> salComp = new TreeSet<Empl>(new MySalaryComp());
    salComp.add(new Empl("R", 3));
    salComp.add(new Empl("J", 6));
    salComp.add(new Empl("C", 20));
    salComp.add(new Empl("T", 2));
    System.out.println(salComp);

  }
}

class MyNameComp implements Comparator<Empl> {

  @Override
  public int compare(Empl e1, Empl e2) {
    return e1.getName().compareTo(e2.getName());
  }
}

class MySalaryComp implements Comparator<Empl> {

  @Override
  public int compare(Empl e1, Empl e2) {
    if (e1.getSalary() > e2.getSalary()) {
      return 1;
    } else {
      return -1;
    }
  }
}

class Empl {

  private String name;
  private int salary;

  public Empl(String n, int s) {
    this.name = n;
    this.salary = s;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int salary) {
    this.salary = salary;
  }

  public String toString() {
    return "Name: " + this.name + "-- Salary: " + this.salary;
  }
}

The code above generates the following result.