-
-
-
代码实现:import java.util.Comparator;
import java.util.TreeSet;
public class TreeSet排序方法 {
public static void main(String[] args) {
TreeSet<String> treeSet=new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int i=o1.length()-o2.length();
i=i==0?o1.compareTo(o2):i;
return i;
}
});
treeSet.add("a");
treeSet.add("ab");
treeSet.add("df");
treeSet.add("aweq");
System.out.println(treeSet);
}
} - TreeSet的案例
- 代码实现:
mport java.util.TreeSet;
public class treeset练习 {
public static void main(String[] args) {
student2 s1 = new student2("张三", 23, 90, 99, 50);
student2 s2 = new student2("李四", 24, 90, 98, 50);
student2 s3 = new student2("王五", 25, 95, 100, 30);
student2 s4 = new student2("赵六", 26, 60, 99, 70);
student2 s5 = new student2("钱七", 26, 70, 80, 70);
TreeSet<student2> treeSet=new TreeSet<>();
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
treeSet.add(s5);
// System.out.println(treeSet);//直接打印未定义排序方法会报错
for (student2 student2 : treeSet) {
System.out.println(student2);
}
}
}
class student2 implements Comparable<student2> {
private String name;
private int age;
private int chinese;
private int math;
private int english;
public student2(String name, int age, int chinese, int math, int english) {
this.name = name;
this.age = age;
this.chinese = chinese;
this.math = math;
this.english = english;
}
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;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "student2{" +
"name='" + name + '\'' +
", age=" + age +
", chinese=" + chinese +
", math=" + math +
", english=" + english +
'}';
}
@Override
public int compareTo(student2 o) {
int sum1=this.getChinese()+this.math+this.getEnglish();
int sum2=o.getChinese()+o.math+o.getEnglish();
int i=sum1-sum2;
//比较两者总分
i=i==0?this.getChinese()-o.getChinese():i;
//总分一样按照语文排序
i=i==0?this.getMath()-o.getMath():i;
// //数学一样按照语文排序
i=i==0?this.getEnglish()-this.getEnglish():i;
i=i==0?this.getAge()-o.getAge():i;
i=i==0?this.getName().compareTo(o.getName()):i;
return i;
}
} -
小结:
-
TreeSet第二种排序方法(比较器排序)
发布时间 2023-04-12 17:45:31作者: 为TT