有没有办法在java中创建条件比较器?

时间:2014-12-25 09:42:45

标签: java comparator

假设我有一个包含三个字段的类:

class Component {
    private String color;
    private int weight;
    private TreeSet<Component> components = new TreeSet<Component>(new CustomComparator());
}

有没有办法创建CustomComparator,以便它根据颜色将组件分类到TreeSet中,当且仅当所有组件具有相同的权重(否则,它根据它们的重量对它们进行排序),而不必创建其他比较器或方法?

1 个答案:

答案 0 :(得分:5)

不确定

new Comparator<Component>() {
  @Override public int compare(Component left, Component right) {
    int cmp = Integer.compare(left.weight, right.weight);
    if (cmp == 0) {
      cmp = left.color.compareTo(right.color);
    }
    return cmp;
  }
};

或者,如果您可以使用第三方库,Guava的ComparisonChain可以让它更加出色:

new Comparator<Component>() {
  @Override public int compare(Component left, Component right) {
    return ComparisonChain.start()
       .compare(left.weight, right.weight)
       .compare(left.color, right.color)
       .result();
  }
};

或者,如果您使用的是Java 8:

Comparator.comparingInt(Component::getWeight) // must have a getter
   .thenComparing(Component::getColor);