• 通过stream对list集合中对象的多个字段进行去重


    记录下通过stream流对list集合中对象的多个字段进行去重!

    举个栗子,对象book,我们要通过姓名和价格这两个字段的值进行去重,该这么做呢?

    •  distinct()返回由该流的不同元素组成的流。distinct()是Stream接口的方法。distinct()使用hashCode()和equals()方法来获取不同的元素。因此,我们的类必须实现hashCode()和equals()方法。

    要在实体类Book中重写hashCode()和equals()方法,比如:

    1. import lombok.Data;
    2. @Data
    3. public class Book {
    4. private String name;
    5. private String author;
    6. private int price;
    7. public Book(String name, String author, int price) {
    8. this.name = name;
    9. this.author = author;
    10. this.price = price;
    11. }
    12. @Override
    13. public boolean equals(final Object obj) {
    14. if (obj == null) {
    15. return false;
    16. }
    17. final Book book = (Book) obj;
    18. if (this == book) {
    19. return true;
    20. } else {
    21. return (this.name.equals(book.getName()) && this.price == book.price);
    22. }
    23. }
    24. @Override
    25. public int hashCode() {
    26. int hashno = 7;
    27. hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
    28. return hashno;
    29. }
    30. }

    然后测试类如下:

    1. /**
    2. * stream流通对象中几个属性的值来进行去重
    3. */
    4. public class Test1 {
    5. public static void main(String[] args) {
    6. List<Book> list = new ArrayList<>();
    7. {
    8. list.add(new Book("水浒传","施耐庵", 200));
    9. list.add(new Book("水浒传", "施耐庵1", 200));
    10. list.add(new Book("三国演义", "罗贯中", 150));
    11. list.add(new Book("西游记", "吴承恩", 300));
    12. list.add(new Book("西游记", "吴承恩2", 300));
    13. }
    14. long l = list.stream().distinct().count();
    15. System.out.println("No. of distinct books:"+l);
    16. list.stream().distinct().forEach(b -> System.out.println(b.getName()+ "," + b.getPrice()));
    17. list = list.stream().distinct().collect(Collectors.toList());
    18. }
    19. }

    运行结果如下:

    ba

    同样,如果是通过三个或者更多的字段进行去重,则只需在Book类中的equals方法中添加该字段即可!

  • 相关阅读:
    vue指令(代码部分二)
    面试经典150题——Day14
    hive 创建 s3 外表
    会议OA之待开会议&所有会议
    通过pyserial操作串口
    Sonar Java默认的扫描规则
    腾讯云COS+picgo+typora 图床搭建与自动上传
    ONNX--学习笔记
    Rust语言——小小白的入门学习05
    Web Audio API 第5章 音频的分析与可视化
  • 原文地址:https://blog.csdn.net/qq_38797181/article/details/133882347