list.stream().distinct().collect(Collectors.toList());
@Data
public class Book {
private Long id;
private String name;
private Double price;
}
bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new));
bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(book -> book.getName() + "-" + book.getPrice()))), ArrayList::new));
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)]