1. List单个字段去重
list.stream().distinct().collect(Collectors.toList());
2. List对象集合根据一个或者多个字段去重
准备类:
@Datapublic class Book { private Long id; private String name; private Double price;}
(1)根据单字段name去重
bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new));
(2)根据多字段name price去重
bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(book -> book.getName() + "-" + book.getPrice()))), ArrayList::new));
(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; @Datapublic 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<Book> 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<Book> bookList1 = bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new)); System.out.println("单字段去重结果:" + bookList1.toString()); // 根据多字段name price去重 List<Book> 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)]
来源地址:https://blog.csdn.net/qq_42546307/article/details/130520716