【发布时间】:2019-12-04 10:43:01
【问题描述】:
我是 Java 流的新手,我现在正在玩它们。鉴于我收到了一份人员列表,我想检测其中哪些人重复并将其打印为“{Id1} 与 {Id3}{Id4} 重复,其重复值为姓名、姓氏、家庭名和生日”
所以这是我的 person 类,我已经重写了 equals 方法,以便根据我的标准获得重复项
public class Person {
private int id;
private String name;
private String familyName;
private String birthday;
private String city;
public Person(int id, String name, String familyName, String birthday, String city) {
this.id = id;
this.name = name;
this.familyName = familyName;
this.birthday = birthday;
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public int hashCode() {
return Objects.hash( name,familyName,birthday,city);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return false;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (!Objects.equals(name, other.name)) {
return false;
}
if (!Objects.equals(familyName, other.familyName)) {
return false;
}
if (!Objects.equals(birthday, other.birthday)) {
return false;
}
return true;
}
}
然后,我通过以下方法获取重复列表
personList.stream()
.filter(p -> personList.contains(p))
.collect(Collectors.toList()).forEach(p-> {
System.out.println(p.getId() + " " + p.getName() + " " + p.getFamilyName() + " " + p.getBirthday());
});
它打印以下内容:
- 2 安德烈斯·冈萨雷斯 12/4/1990
- 4 莫琳·佩雷斯 15/07/92
- 7 安德烈斯·冈萨雷斯 1990 年 12 月 4 日
- 9 莫琳·佩雷斯 15/07/92
- 11 莫琳佩雷斯 15/07/92
如您所见,ID 的 2 和 7 是重复的,4,9 和 11 也是重复的,这些是我需要以该格式打印的那些,但我不知道如何使用流来做到这一点.
【问题讨论】:
-
personList.stream().filter(p -> personList.contains(p))最好执行forEach,因为p始终包含在personList中。
标签: java list java-stream