有勇气的牛排博客

Set集合 TreeSet 比较器排序Comparator的使用

有勇气的牛排 1555 Java 2021-08-23 23:47:20

1 Comparator的使用

1、用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序的

2、比较器排序,就是让集合构造方接收Comparator的实现类对象,重写compare(T o1, T o2)方法

3、重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写

2 介绍

1、存储学生对象并遍历,创建TreeSet集合使用的带参构造方法

2、要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

3 实战演练

package Comparator; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package Comparator; import java.util.Comparator; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { // 创建集合对象 TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num = s1.getAge() - s2.getAge(); int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num; return num2; } }); // 创建学生对象 Student s1 = new Student("xishi", 20); Student s2 = new Student("wangzhaojun", 26); Student s3 = new Student("diaochan", 30); Student s4 = new Student("yangyuhuan", 22); Student s5 = new Student("tom", 22); // 把学生添加到集合 ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); // 遍历集合 for (Student s : ts) { System.out.println(s.getName() + "," + s.getAge()); } } }

留言

专栏
文章
加入群聊