Java TreeSet 添加自定义对象 必须指定排序规则
package com.zhong.collection.set;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Stu> stus = new TreeSet<>((Comparator.comparingInt(Stu::getAge)));
stus.add(new Stu("小钟", 22));
stus.add(new Stu("小钟", 22));
stus.add(new Stu("小王", 21));
stus.add(new Stu("张三", 60));
stus.add(new Stu("张三", 80));
for (Stu student : stus) {
System.out.println(student);
}
}
}
class Stu {
private String name;
private int age;
public Stu() {
}
public Stu(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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}