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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM