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); });

運行結果: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; } }
相關文章
相關標籤/搜索