//set去重(list集合–>set集合)
public class SetMethod {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(3);
list1.add(1);
list1.add(2);
list1.add(5);
Set<Integer> set = new HashSet<>();
set.addAll(list1);
list1.clear();//先清空之后再添加所有
list1.addAll(set);
Collections.sort(list1);//Collections.sort();参数是List集合
System.out.println(list1);
}
}
//外部比较器:Comparator
public class SortMethod1 {
public static void main(String[] args) {
List<Student> stu = new ArrayList<>();
stu.add(new Student("liusan",20,90.0F));
stu.add(new Student("lisi",22,90.0F));
stu.add(new Student("wangwu",20,99.0F));
stu.add(new Student("wangwu",22,100.F));
Collections.sort(stu, new Comparator<Student>() {//参数里面包含一个匿名
@Override
public int compare(Student o1, Student o2) {
double result = o2.getScore() - o1.getScore();//o1-o2升序排列
if (result == 0) { //o2-o1降序排列
result = o1.getAge() - o2.getAge();
} return (int) result;
}
});
System.out.println(stu);
}
}
//内部比较器:差异:需要有一个学生类连接Comparable接口
public class SortMethod2 {
public static void main(String[] args) {
List<Student> stu = new ArrayList<>();
stu.add(new Student("liusan",20,90.0F));
stu.add(new Student("lisi",22,90.0F));
stu.add(new Student("wangwu",20,99.0F));
stu.add(new Student("wangwu",22,100.F));
Collections.sort(stu);
System.out.println(stu);
}
}
public class Student implements Comparable<Student> {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
//覆盖重写Comparable
@Override
public int compareTo(Student o) {
double result = o.getScore() - this.getScore();//this.-o.升序
if (result == 0) { //o.-this.降序
result = this.getAge() - o.getAge();
} return (int) result;
}