1. 程式人生 > >Guava 系列 - 比較器

Guava 系列 - 比較器

文章目錄

Guava 系列 - 比較器


1、自我實現的比較器例子
class Person implements Comparable<Person> {
  private String lastName;
  private String firstName;
  private int zipCode;

  public int compareTo(Person other) {
    int cmp = lastName.compareTo(other.lastName);
    if (cmp != 0) {
      return cmp;
    }
    cmp = firstName.compareTo(other.firstName);
    if (cmp != 0) {
      return cmp;
    }
    return Integer.compare(zipCode, other.zipCode);
  }
}
2、使用guava比較器

上面的程式碼比較冗長,而且容易出錯
guava 提供一個 ComparisonChain 類用於比較,只要找到一個非0結果,即不相同就立即停止比較,以獲得更好的效能

// 我們只需要通過 ComparisonChain 構建的比較器進行簡單的比較即可
public class Foo implements Comparable<Foo> {


    private String name;
    private String realName;
    private String code;


    @Override
    public int compareTo(Foo that) {

        return ComparisonChain.start()
                .compare(this.name, that.name)
                .compare(this.realName, that.realName)
                .compare(this.code, that.code)
                .result();
    }
}