Учитывая два класса бинов, например,
@Immutable
static class Person {
private final String firstName;
private final String secondName;
private final String phoneNumber;
public Person(String firstName, String secondName, String phoneNumber) {
this.firstName = firstName;
this.secondName = secondName;
this.phoneNumber = phoneNumber;
}
public String getFirstName() {
return this.firstName;
}
public String getSecondName() {
return this.secondName;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
}
@Immutable
static class Company {
private final String name;
private final String phoneNumber;
public Company(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return this.name;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
}
, общие свойства могут быть помещены в третий класс, например,
static class CommonData {
private final String phoneNumber;
public CommonData(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ListComparisTest.CommonData) {
ListComparisTest.CommonData rhs = (ListComparisTest.CommonData) obj;
return new EqualsBuilder()
.append(this.phoneNumber, rhs.phoneNumber)
.isEquals();
}
return false;
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(phoneNumber)
.toHashCode();
}
}
и два списка, сравниваемых как этот
@Test
public void testCompareLists() {
Function<Person, CommonData> person2CommonData = p->new CommonData(p.getPhoneNumber());
Function<Company, CommonData> company2CommonData = c->new CommonData(c.getPhoneNumber());
List<Person> persons = Arrays.asList(new Person("James", "Cook", "1234566" ), new Person("Francis", "Drake", "2345667" ));
List<Company> companys = Arrays.asList(new Company("Google", "1234566" ), new Company("IBM", "2345667" ));
List<CommonData> personsCommonData = persons.stream().map(person2CommonData).collect(Collectors.toList());
List<CommonData> companysCommonData = companys.stream().map(company2CommonData).collect(Collectors.toList());
Assert.assertTrue(personsCommonData.equals(companysCommonData));
}