想整个简单的去重
package com.wangwei.common;
import java.util.*;
public class Test1 {
static List<Student> studentList = new ArrayList<>();
static {
Student p1 = new Student();
p1.setName("小米");
p1.setAge(18);
Student p2 = new Student();
p2.setName("小米");
p2.setAge(19);
Student p3 = new Student();
p3.setName("小华");
p3.setAge(19);
Student p4 = new Student();
p4.setName("小华");
p4.setAge(19);
studentList.add(p1);
studentList.add(p2);
studentList.add(p3);
studentList.add(p4);
}
public static void main(String[] args) {
testRemoveJava();
testRemove8();
testRemove5();
}
static void testRemove8() {
Set<Student> studentSet = new TreeSet<>(Comparator.comparing(o -> (o.getName())));
studentSet.addAll(studentList);
System.out.println("testRemove8()");
new ArrayList<>(studentSet).forEach(System.out::println);
}
static void testRemoveJava() {
System.out.println("testRemoveJava()");
Set<Student> studentSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//o1.getName().compareTo(o2.getName()); 倒序
//o2.getName().compareTo(o1.getName()); 正序
return o2.getName().compareTo(o1.getName());
}
});
studentSet.addAll(studentList);
//把set集合转成list
ArrayList<Student> students = new ArrayList<>(studentSet);
for (Student student : students) {
System.out.println(student.toString());
}
}
static void testRemove5() {
Set<Student> studentSet = new TreeSet<>(Comparator.comparing(Student::getName));
studentSet.addAll(studentList);
System.out.println("testRemove5()");
new ArrayList<>(studentSet).forEach(System.out::println);
}
}
搞个自定义的去重