集合中为一个类,根据类中某两种属性确定是否为同一对象,
bean:Cat
重写了 equals 方法和 hashCode 方法,更改确定为唯一对象的两种属性(此时为 name 和 age ),只重写 equals 方法或 hashCode 方法都不行,
package com.zjxt.demo.pojo.bean;
import java.util.Objects;
/**
* @Author: heiheihaxi
* @Date: 2019/9/24 15:32
*/
public class Cat {
private String name;
private String age;
private String color;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cat cat = (Cat) o;
return Objects.equals(name, cat.name) &&
Objects.equals(age, cat.age) ;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", color='" + color + '\'' +
", type='" + type + '\'' +
'}';
}
}
测试类:
通过使用 stream.distinct()方法去重,会根据对象的相等的方法去重。
package com.zjxt.demo.test.collectortest;
import com.zjxt.demo.pojo.bean.Cat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsTest5 {
public static void main(String[] args) {
List<Cat> list = new ArrayList<>();
Cat cat1 = new Cat();
cat1.setName("aaa");
cat1.setAge("11");
Cat cat2 = new Cat();
cat2.setName("bbb");
cat2.setAge("12");
Cat cat3 = new Cat();
cat3.setName("bbb");
cat3.setAge("11");
Cat cat4 = new Cat();
cat4.setName("aaa");
cat4.setAge("12");
Cat cat5 = new Cat();
cat5.setName("aaa");
cat5.setAge("11");
cat5.setColor("black");
list.add(cat1);
list.add(cat2);
list.add(cat3);
list.add(cat4);
list.add(cat5);
ArrayList<Cat> collect = list.stream().distinct().collect(Collectors.toCollection(ArrayList::new));
System.out.println(collect.size());
System.out.println(collect);
}
}