• 通过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方法中添加该字段即可!

  • 相关阅读:
    【PyTorch】torch.nn.functional.interpolate——采样操作
    911. 在线选举
    1723_PolySpace Bug Finder命令行执行探索
    品牌监控用到API接口,可以实现以下功能:
    问chatgpt最近生活的困难
    Elasticsearch mapping
    mysql、oracle 构建数据
    Python单例模式详解与实际应用
    Vue3 路由优化,使页面初次渲染效率翻倍
    建筑楼宇VR火灾扑灭救援虚拟仿真软件厂家
  • 原文地址:https://blog.csdn.net/qq_38797181/article/details/133882347