[英]Get duplicated items with specific format from Java Stream
我是 Java 流的新手,我現在正在玩它們。 鑒於我收到一個人名單,我想檢測哪些人是重復的,並將它們打印為“{Id1} 與 {Id3}{Id4} 重復,其重復值是姓名、姓氏、家庭姓名和生日”
所以這是我的個人類,我已經覆蓋了 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());
});
它打印以下內容:
如您所見,ID 的 2 和 7 是重復的,並且 4,9 和 11 也是重復的,這些是我需要以該格式打印的那些,但到目前為止我不知道如何使用流進行打印。
首先,您應該修復您的hashCode()
實現以匹配您的equals
。 如果兩個對象相等,則它們必須具有相同的hashCode()
。
現在,您的Stream
管道返回所有元素,因為您的filter
的Predicate
將始終返回true
。
相反,您可以將List
相等元素分組:
Map<Person,List<Integer>> grouped =
personList.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.mapping(Person::getId,
Collectors.toList())));
現在,對於每個Person
,您都有一個關聯的標識符List
。 您可以迭代此Map
並打印具有大小 > 1 的List
的Person
。
例如:
personList.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.mapping(Person::getId,
Collectors.toList())));
.entrySet()
.stream()
.filter(e -> e.getValue().size() > 1)
.forEach(e -> System.out.println(e.getKey().getId() + " " + e.getKey().getName() + " " + e.getKey().getFamilyName() + " " + e.getKey().getBirthday() + " " + e.getValue()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.