Java中list集合stream流去重 1. List单个字段去重 list.stream().distinct().collect(Collectors.toList()); 2. List对象
list.stream().distinct().collect(Collectors.toList());
准备类:
@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
--结束END--
本文标题: Java中list集合stream流去重
本文链接: https://lsjlt.com/news/408914.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0