做代金券的网站,什么是网站源码,急求聊城网站建设,医院电子网站建设记录下通过stream流对list集合中对象的多个字段进行去重#xff01;
举个栗子#xff0c;对象book#xff0c;我们要通过姓名和价格这两个字段的值进行去重#xff0c;该这么做呢#xff1f; distinct#xff08;#xff09;返回由该流的不同元素组成的流。distinct
举个栗子对象book我们要通过姓名和价格这两个字段的值进行去重该这么做呢 distinct返回由该流的不同元素组成的流。distinct是Stream接口的方法。distinct使用hashCode和equals方法来获取不同的元素。因此我们的类必须实现hashCode和equals方法。
要在实体类Book中重写hashCode和equals方法比如
import lombok.Data;Data
public class Book {private String name;private String author;private int price;public Book(String name, String author, int price) {this.name name;this.author author;this.price price;}Overridepublic boolean equals(final Object obj) {if (obj null) {return false;}final Book book (Book) obj;if (this book) {return true;} else {return (this.name.equals(book.getName()) this.price book.price);}}Overridepublic int hashCode() {int hashno 7;hashno 13 * hashno (name null ? 0 : name.hashCode());return hashno;}}
然后测试类如下
/*** stream流通对象中几个属性的值来进行去重*/public class Test1 {public static void main(String[] args) {ListBook list new ArrayList();{list.add(new Book(水浒传,施耐庵, 200));list.add(new Book(水浒传, 施耐庵1, 200));list.add(new Book(三国演义, 罗贯中, 150));list.add(new Book(西游记, 吴承恩, 300));list.add(new Book(西游记, 吴承恩2, 300));}long l list.stream().distinct().count();System.out.println(No. of distinct books:l);list.stream().distinct().forEach(b - System.out.println(b.getName() , b.getPrice()));list list.stream().distinct().collect(Collectors.toList());}}
运行结果如下
ba
同样如果是通过三个或者更多的字段进行去重则只需在Book类中的equals方法中添加该字段即可