[Java基础]比较器排序Comparator的使用
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]比较器排序Comparator的使用相关的知识,希望对你有一定的参考价值。
代码如下:
package ComparablePack;
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 ComparablePack;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo01 {
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("Tom",13);
Student s2 = new Student("Jack",17);
Student s3 = new Student("Lily",29);
Student s4 = new Student("Jbck",17);
Student s5 = new Student("Jack",17);
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());
}
}
}
以上是关于[Java基础]比较器排序Comparator的使用的主要内容,如果未能解决你的问题,请参考以下文章
Java 8 新特性:Comparator.naturalOrder | 自然排序
Java学习总结——(Map集合,Comparator接口,异常等)