【java8】使用lambda表達式對List去重

 

先收集再排序。ide

 

public static void main(String[] args) {

        BookBo bookBo1 = new BookBo("1", "語文");
        BookBo bookBo2 = new BookBo("2", "數學");
        BookBo bookBo3 = new BookBo("3", "英語");
        BookBo bookBo4 = new BookBo("4", "地理");
        BookBo bookBo5 = new BookBo("5", "生物");
        BookBo bookBo6 = new BookBo("1", "語文");
        List<BookBo> bookBoList = Arrays.asList(bookBo1, bookBo2, bookBo3, bookBo4, bookBo5, bookBo6);

        List<BookBo> distinctList = bookBoList
                //collectingAndThen收集而後在
                .stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(o-> o.getName()))), ArrayList::new))
                .stream().sorted(Comparator.comparing(BookBo::getName)).collect(Collectors.toList());

        System.out.println(distinctList);
    }

 

 

public class BookBo implements Serializable {

    private static final long serialVersionUID = 587389645684120455L;

    private String name;
    private String author;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public BookBo() {
    }

    public BookBo(String name, String author) {
        this.name = name;
        this.author = author;
    }

    @Override
    public String toString() {
        return "BookBo{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}
相關文章
相關標籤/搜索