目录
1 TreeSet实现自动排序
@Test
public void testCalculate() {
Student stu1 = new Student("张三", 80);
Student stu2 = new Student("李四", 60);
Student stu3 = new Student("王二", 90);
Student stu4 = new Student("麻子", 70);
// 定义排序类型,按照分数排序
TreeSet<Student> stuSet = new TreeSet<>(Comparator.comparingInt(Student::getScore));
//添加数据的时候排序
stuSet.add(stu1);
stuSet.add(stu2);
stuSet.add(stu3);
stuSet.add(stu4);
for(Student stu: stuSet){
System.out.println(stu);
}
System.out.println("******************************");
//更改数据不会影响原来的顺序,TreeSet使用的时候最好不要修改数据
stu4.setScore(95);
for(Student stu: stuSet){
System.out.println(stu);
}
}
测试结果
Student(name=李四, score=60)
Student(name=麻子, score=70)
Student(name=张三, score=80)
Student(name=王二, score=90)
******************************
Student(name=李四, score=60)
Student(name=麻子, score=95)
Student(name=张三, score=80)
Student(name=王二, score=90)
2 TreeMap实现自动排序
@Test
public void testCalculate() {
Student stu1 = new Student("张三", 80);
Student stu2 = new Student("李四", 60);
Student stu3 = new Student("王二", 90);
Student stu4 = new Student("麻子", 70);
TreeMap<Student, String> stuMap = new TreeMap<>(Comparator.comparingInt(Student::getScore));
//添加数据的时候排序
stuMap.put(stu1, "");
stuMap.put(stu2, "");
stuMap.put(stu3, "");
stuMap.put(stu4, "");
for (Student student : stuMap.keySet()) {
System.out.println(student);
}
System.out.println("******************************");
//更改数据不会影响原来的顺序,TreeMap使用的时候最好不要修改数据
stu4.setScore(95);
for (Student student : stuMap.keySet()) {
System.out.println(student);
}
}
测试结果:
Student(name=李四, score=60)
Student(name=麻子, score=70)
Student(name=张三, score=80)
Student(name=王二, score=90)
******************************
Student(name=李四, score=60)
Student(name=麻子, score=95)
Student(name=张三, score=80)
Student(name=王二, score=90)