1. 程式人生 > >Java 8 根據屬性值對列表去重

Java 8 根據屬性值對列表去重

對列表的去重處理,Java 8 在 Stream 介面上提供了類似於 SQL 語句那樣的 distinct() 方法,不過它也只能基於物件整體比較來去重,即通過 equals/hashCode 方法。distinct 方法的功效與以往的 new ArrayList(new HashSet(books)) 差不多。用起來是

List<Book> unique = book.stream().distinct().collect(Collectors.toList())

並且這種去重方式需要在模型類中同時實現 equals 和 hashCode 方法。

回到實際專案中來,我們很多時候的需求是要根據物件的某個屬性來去重。比如接下來的一個例項,一個 books 列表中存在 ID 一樣,name 卻不同的 book, 我們認為這是重複的,所以需要根據 book 的 id 屬性對行去重。在 collect 的時候用到的方法是 collectinAndThen(…), 下面是簡單程式碼:

/**
 * @author wzx
 * @time 2018/2/9
 */
public class Deduplication {
    public static void main(String[] args) {
        List<Book> books = Arrays.asList(
                new Book(12, "Sun Java"),
                new Book(12, "Oracle Java"),
                new Book(15, "Scala")
        );
        List<Book> unique = books.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new
TreeSet<>(Comparator.comparing(o -> o.id))), ArrayList::new) ); unique.forEach(book -> System.out.printf("book[id: %s, name: %s]\n", book.id, book.name)); } } class Book { public final Integer id; public final String name; public Book(Integer id, String name) { this
.id = id; this.name = name; } }

執行後打印出

book[id: 12, name: Sun Java]
book[id: 15, name: Scala]