Java Collection How to - Compare two objects in custom tree set implementation








Question

We would like to know how to compare two objects in custom tree set implementation.

Answer

import java.util.Comparator;
import java.util.TreeSet;
/*w w  w.j a  v a  2s. c  om*/
public class Main {
  public static void main(String a[]) {
    // using name comparator (String comparison)
    TreeSet<Empl> nameComp = new TreeSet<Empl>(new MyNameComp());
    nameComp.add(new Empl("A", 3));
    nameComp.add(new Empl("J", 6));
    nameComp.add(new Empl("C", 2));
    nameComp.add(new Empl("T", 2));
    for (Empl e : nameComp) {
      System.out.println(e);
    }
    // using salary comparator (int comparison)
    TreeSet<Empl> salComp = new TreeSet<Empl>(new MySalaryComp());
    salComp.add(new Empl("A", 3));
    salComp.add(new Empl("J", 6));
    salComp.add(new Empl("C", 2));
    salComp.add(new Empl("T", 2));
    for (Empl e : salComp) {
      System.out.println(e);
    }
  }
}

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.