Oracle去重多个字段,并返回其他所有字段
业务场景:
业务需求1:需要对前端入参进行某个字段或者多个字段去重操作,防止插入重复数据。
业务需求2:多条件下抓取数据列表,需要对数据列表的某个字段或者多个字段进行去重。
例子:
对学生的姓名、年龄去重
public static class Student implements Serializable {
private String name;
private String age;
private String sex;
public Student(String name, String age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", sex='" + sex + '\'' +
'}';
}
}
解决方案:
public static void main(String[] args) {
Student student1 = new Student("11","11","0");
Student student2 = new Student("11","22","1");
Student student3 = new Student("11","22","0");
Student student4 = new Student("11","33","1");
Student student5 = new Student("22","33","0");
List<Student> students = new ArrayList<Student>();
students.add(student1);
students.add(student2);
students.add(student3);
students.add(student4);
students.add(student5);
System.out.println("--------------------对象去重-----------------------");
List<Student> collect = students.stream().distinct().collect(toList());
for (Student student : collect) {
System.out.println(student);
}
System.out.println("-------------------根据多个字段去重--------------------------");
ArrayList<Student> collect1 = students.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(student -> student.getName() + student.getAge())
)), ArrayList::new));
for (Student student : collect1) {
System.out.println(student);
}
}
输出结果集:
Tip:使用了Java8获取字段的方式,比较常用,类似前端的钩子函数,可读性比较明了,但是当你检测哪个字段被哪里地方被引用时,这样写的字段不会被检测到。
评论前必须登录!
注册