If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How you can have only unique objects in this list?
Example:
You have a class called Person:
class Person{
String lastName;
String Email;
}
You have array list of objects contains list of Person
List persons = new ArrayList()
persons.add(new Person("Nasr","mahmoud@goole.com"));
persons.add(new Person("Ali","ali@goole.com"));
persons.add(new Person("Ali","ali@goole.com"));
When last name and email are equals it is considered as duplication.
In order to prevent duplication, you can use distinct method using Lambdas in Java8 from the Stream API .
persons = persons.stream().distinct().collect(Collectors.toList());
Distinct method will use the "equals" method and "hashcode" method which located at the object person by default , so to define the duplication criteria you have to override these methods : @Override
public boolean equals(Object object) {
Person p = (Person ) object;
if(e.lastName == null || e.email == null){
return false;
}
if (e.lastName.equals(this.lastName) && e.email.equals(this.email)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(lastName + email);
}
Now, if you print the list persons it will contains only 2 objects.