You'll need to override equals
and hashcode
to get the expected result.
Example:
class Person {
private String name;
private String theOtherField;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return (name != null ? name.equals(person.name) : person.name == null) &&
(theOtherField != null ? theOtherField.equals(person.theOtherField) :
person.theOtherField == null);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (theOtherField != null ? theOtherField.hashCode() : 0);
return result;
}
public Person(String name, String theOtherField) {
this.name = name;
this.theOtherField = theOtherField;
}
}
Now, assuming you have a list of people like this for example:
List<Person> personList = Arrays.asList(new Person("nameA", "35"),
new Person("nameA", "35"));
Performing the distinct
operation should yield a list with one element.
List<Person> distinctPeople =
personList.stream()
.distinct()
.collect(Collectors.toList());
or you can collect to a Set
implementation without using distinct
like this:
Set<Person> distinctPeople = new HashSet<>(personList);
Note, I've named one of the properties in the Person
class theOtherField
because I don't know whether it represents the person's age or not as ideally a person's age should be an int
not String
.