先收集再排序。
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 + '\'' + '}'; } }
全文完,感谢您的耐心阅读~
欢迎大家关注我的公众号