Perhaps you should consider using java.util.Set
and java.util.TreeSet
for natural ordering(if needed be). The Set
interface specification ensures, that no two equal objects exist in a Set
.
Override Animal#equals
, Animal#hashcode
and implements Comparable
interface. For example:-
public class Animal implements Comparable<Animal>{
private final String name;
private final boolean hasEyes;
public Animal(String name, boolean eyes){
this.name = name;
this.hasEyes = eyes;
}
public String getName() {
return name;
}
public boolean isHasEyes() {
return hasEyes;
}
@Override
public int hashCode() {
int hash = 5;
hash = 29 * hash + Objects.hashCode(this.name);
hash = 29 * hash + (this.hasEyes ? 1 : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Animal other = (Animal) obj;
if (this.hasEyes != other.hasEyes) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
@Override
public int compareTo(Animal o) {
//....compareTo implementation.
}
}
Finally "intersections" between 2 List<Animal>
consolidated into a Set<Animal>
.
Set<Animal> s = new TreeSet<>();
s.addAll(allAnimals);
s.addAll(animalWithEyes);
The Set#addAll
implementation ensure no duplicate Animal
exist.
*** Or you could use project Lombok annotations to generate equals
, hashcode
and Comparable
implementations.