通过stream对list集合中对象的多个字段进行去重
记录下通过stream流对list集合中对象的多个字段进行去重!
举个栗子,对象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) {List<Book> 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方法中添加该字段即可!