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;
}
(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)示例文章来源:https://www.toymoban.com/news/detail-697856.html
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<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());
}
}
输出打印结果文章来源地址https://www.toymoban.com/news/detail-697856.html
单字段去重结果:[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中list集合stream流去重的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!