在Java中,您可以通过以下几种方式组合多个Comparator:
Comparator.thenComparing(): 这种方法允许您基于一个Comparator的结果,然后根据第二个Comparator进行排序。例如:import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Person[] people = new Person[]{
new Person("John", 25),
new Person("Jane", 22),
new Person("John", 20)
};
Comparator<Person> byName = Comparator.comparing(Person::getName);
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Arrays.sort(people, byName.thenComparing(byAge));
System.out.println(Arrays.toString(people));
}
}
Comparator.comparing(): 这种方法允许您基于一个Comparator的结果进行排序,如果结果相等,则使用另一个Comparator。例如:import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Person[] people = new Person[]{
new Person("John", 25),
new Person("Jane", 22),
new Person("John", 20)
};
Comparator<Person> byName = Comparator.comparing(Person::getName);
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Arrays.sort(people, Comparator.comparing(Person::getName).thenComparingInt(Person::getAge));
System.out.println(Arrays.toString(people));
}
}
Comparator.thenComparing(): 这种方法允许您基于多个属性进行排序。例如:import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Person[] people = new Person[]{
new Person("John", 25),
new Person("Jane", 22),
new Person("John", 20)
};
Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
Comparator<Person> byFirstName = Comparator.comparing(Person::getFirstName);
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);
Arrays.sort(people, byLastName.thenComparing(byFirstName).thenComparing(byAge));
System.out.println(Arrays.toString(people));
}
}
在这些示例中,我们首先根据姓名对Person对象进行排序,然后根据年龄进行排序。您可以根据需要添加更多的Comparator来组合多个排序条件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。