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); });
運行結果:this
Student(id=3, name=小粉, city=廣州)
Student(id=1, name=小紅, city=重慶)
Student(id=2, name=小綠, city=北京)spa
@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; } }