Java 比较对象列表以查找重复项并将它们放入新列表中



当比较同一对象的两个列表以查找它们重复的位置时,两个列表都为空。

List<Appointment> appointmentByName = sM.getAppointmentByName(first.getText(),last.getText());
List<Appointment>appointmentByDate=sM.getAppointmentByDate(LocalDate.now());System.out.println(appointmentByName);
//Populating the lists (This works)

List<Appointment> common = appointmentByDate.stream().filter(appointmentByName::contains).collect(toList());

填充列表后,我想找到相同的约会对象并将它们放入新列表中,例如

List1 [Appointment@20, Appointment@c3, Appointment@d9, Appointment@175]
List2 [Appointment@23, Appointment@175]
List3 [Appointment@175]

约会类中的等于重写

public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Appointment)) return false;
    Appointment that = (Appointment) o;
    return id == that.id;
}

但是,公共列表是空的,任何帮助都是值得赞赏的。

不确定我是否正确理解了您的问题,但在我看来,您正在尝试在此处进行两个列表的交集。如果是,您可以使用 Collection 的 retainAll(( 方法执行此操作:

list1.retainAll(list2)

list1 现在将仅包含两个列表的重复项

Soloution;将约会类中的等于重写从

public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Appointment)) return false;
Appointment that = (Appointment) o;
return id == that.id;
}

public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Appointment)) return false;
Appointment that = (Appointment) o;
return id.equals(that.id);
}

相关内容

  • 没有找到相关文章

最新更新