list实体类preple类 有四个属性 id name age sex 现在list存了五个对象
五个实体类分别为 1 张三 18 男
2 张三 18 男
3 李四 20 男
4 李四 18 男
现在需要根据name和sex 查出重复的存在一个list中
list实体类preple类 有四个属性 id name age sex 现在list存了五个对象
五个实体类分别为 1 张三 18 男
2 张三 18 男
3 李四 20 男
4 李四 18 男
现在需要根据name和sex 查出重复的存在一个list中
我看上面已经有一些案例,可以解决对应问题。我换一种实现方式:
我是通过重写对象的hashCode和equals方法,并通过set集合不存放重复集合的原理实现的。
copy代码执行下,哪里不明白可以私聊讨论下。
import java.util.*;
/**
* ListDistinctCase
*/
public class ListDistinctCase {
/**
* 模拟查出来的person集合
*/
static List<Person> personList = new ArrayList<Person>(6) {{
add(new Person("1", "张三", 18, "男"));
add(new Person("2", "张三", 18, "男"));
add(new Person("3", "李四", 20, "男"));
add(new Person("4", "李四", 18, "男"));
}};
public static void main(String[] args) {
// 利用set集合插入对象不重复的原理,所以使用set集合
Set<Person> personSet = new HashSet<>();
// 重复人员存储集合
List<Person> repeatResultList = new ArrayList<>(6);
personList.forEach(person -> {
if (!personSet.add(person)) {
// 如果set中添加对象失败,说明name和sex属性重复,将重复对象添加至repeatResultList中
// 因为你重写person的Equals和HashCode方法,所以会根据重写的这2个方法判定对象是否重复
repeatResultList.add(person);
}
});
repeatResultList.forEach(person -> {
System.out.println("重复人员: " + person);
});
}
private static class Person {
private final String id;
private final String name;
private final Integer age;
private final String sex;
public Person(String id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
/**
* 重写Equals,HashCode方法,方法中仅保留name个sex属性
*
* @param o this
* @return 相等:true,不相等:false
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return Objects.equals(name, person.name) && Objects.equals(sex, person.sex);
}
@Override
public int hashCode() {
return Objects.hash(name, sex);
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
}