I am attempting to create a TreeMap
with the following Format:
TreeMap<Kenel, List<Dog>> treeMapOfKennelsAndDogs;
Each entry is a Kennel
object with an attached list of Dogs
. I want to compare each Kennel by the oldest Dog in each and order accordingly.
However the order of the treeMap
is not what I am expecting, it seems that when a Kennel has a Dog List of size 1 in the list then the ordering is incorrect.
Below is my code to find the oldest Dog related to each Kennel, and also my comparator logic.
@Entity
@Table(name = "KENNEL")
public class Kennel {
//other fields
@OneToMany(cascade = CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "KENNEL_ID", referencedColumnName = "ID", updatable = true, insertable = true)
private List<Dog> dogList;
public DateTime getOldestDogInList() {
if (dogList.size() == 0) {
return null; }
Dog dog= dogList.get(0);
for (int i = 1; i < dogList.size(); i++) {
dog d = dogList.get(i);
if (d.getCreated().isBefore(dog.getCreated())) {
dog = d;
}
}
return dog.getCreated();
}
Comparator logic in service class:
Comparator<Kennel> oldestDog = new Comparator<Kennel>() {
@Override
public int compare(Kennel k1, Kennel k2) {
int result = k1.getOldestDogInList().compareTo(k2.getOldestDogInList());
return result;
}
};
TreeMap<Kennel, List<Dog>> treeMapOfKennelsAndDogs = new TreeMap<>(oldestDog);
Is there an error in code that would cause the incorrect ordering in the TreeMap?