java1.8 根据list内某个字段值,条件去重后获取新的list
List<Student> list = new ArrayList<>(); list.add(new Student(1, "小红", "重庆")); list.add(new Student(2, "小绿", "北京")); list.add(new Student(3, "小粉", "广州")); list.add(new Student(4, "小红", "")); list.add(new Student(5, "小红", "重庆")); List<Student> newList = list.stream() .filter(student -> StringUtils.isNotBlank(student.getCity())) .collect(Collectors.collectingAndThen(Collectors.toCollection( () -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new)); newList.forEach(student -> { System.out.println(student); });
运行结果:
Student(id=3, name=小粉, city=广州)
Student(id=1, name=小红, city=重庆)
Student(id=2, name=小绿, city=北京)
@Data public class Student { private Integer id; private String name; private String city; public Student(Integer id, String name, String city) { this.id = id; this.name = name; this.city = city; } }