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

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


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

最佳答案

当然。

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);

关于java - 有没有办法在Java中创建条件比较器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27646036/

10-13 05:03