1.测试代码示例
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
@Slf4j
public class test {
public static void main(String[] args) {
//1.构造测试数据
List<Student> oldStudents = new ArrayList<>();
Student student1 = new test().new Student();
student1.setName("小王");
student1.setOnlyKey("123");
oldStudents.add(student1);
Student student2 = new test().new Student();
student2.setName("小王");
student2.setOnlyKey("123");
oldStudents.add(student2);
Student student3 = new test().new Student();
student3.setName("小孙");
student3.setOnlyKey("123444");
oldStudents.add(student3);
log.info("去重之前的数据:{}", JSON.toJSONString(oldStudents));
//java8 去重
List<Student> newStudents = oldStudents.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getOnlyKey))), ArrayList::new)
);
log.info("去重之后的数据:{}",JSON.toJSONString(newStudents));
}
@Data
class Student {
private String name;
private String onlyKey;
}
}
2.测试结果
3.适用场景
像从数据库查询数据 selectOne but select many 这种问题,代码中依此可以进行规避处理OvO