1 .主类 |
package s0224TreeSet自动排序; |
//TreeSet 设定了比较器之后,加入的数据自动排序 |
//TreeSet数据可以排序,但不能重复 |
//TreeSet中的元素必须可排序,要么元素是接口comparable实现类的实例,要么给定比较器 |
import java.util.TreeSet; |
public class Main { |
public static void main(String[] args) |
{ |
|
// TreeSet<Student> set1=new TreeSet<Student>(new Comparator<Student>(){ |
// public int compare(Student s1,Student s2) |
// { return s1.getScore()-s2.getScore(); } |
// }); |
// 简化的lambda表达式如下: |
|
TreeSet<Student> set= new TreeSet<Student>( |
(Student s1,Student s2) ->s2.getScore()-s1.getScore() ); //从大到小 |
// (Student s1,Student s2) ->s1.getScore()-s2.getScore() ); //从小到大 |
|
set.add( new Student( "小明" , 80 )); |
set.add( new Student( "小张" , 70 )); |
set.add( new Student( "小黄" , 90 )); |
System.out.println(set); |
} |
|
} |
|
2 .student类 |
package s0224TreeSet自动排序; |
public class Student { |
private String name; |
private int score; |
|
|
public Student(String name, int score) { |
super (); |
this .name = name; |
this .score = score; |
} |
public String toString() |
{ |
return this .name+ " 成绩" + this .score+ "\n" ; |
} |
public String getName() { |
return name; |
} |
public void setName(String name) { |
this .name = name; |
} |
public int getScore() { |
return score; |
} |
public void setScore( int score) { |
this .score = score; |
} |
|
} |