Java中list集合stream流去重

1、List单个字段去重

list.stream().distinct().collect(Collectors.toList());

2、List对象集合根据一个或者多个字段去重

准备类

@Data
public class Book {
    private Long id;
    private String name;
    private Double price;
}

2.1 根据单字段name去重

bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new));

2.2 根据多字段name price去重

bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(book -> book.getName() + "-" + book.getPrice()))), ArrayList::new));

2.3 示例

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import lombok.Data;

@Data
public class Book {
    private Long id;
    private String name;
    private Double price;

    public Book(Long id, String name, Double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public static void main(String[] args) {
        List bookList = new ArrayList<>();
        bookList.add(new Book(1L, "书本1", 1.1));
        bookList.add(new Book(2L, "书本1", 1.1));
        bookList.add(new Book(3L, "书本2", 2.2));
        bookList.add(new Book(4L, "书本2", 4.4));
        // 根据单字段name去重
        List bookList1 = bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new));
        System.out.println("单字段去重结果:" + bookList1.toString());
        // 根据多字段name price去重
        List bookList2 = bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(book -> book.getName() + "-" + book.getPrice()))), ArrayList::new));
        System.out.println("多字段去重结果:" + bookList2.toString());
    }
}

输出打印结果

单字段去重结果:[Book(id=1, name=书本1, price=1.1), Book(id=3, name=书本2, price=2.2)]
多字段去重结果:[Book(id=1, name=书本1, price=1.1), Book(id=3, name=书本2, price=2.2), Book(id=4, name=书本2, price=4.4)]

你可能感兴趣的:(java,开发语言)