目錄
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)