For proper working, Project
needs an additional attribute such as id
:
class Project {
String id;
Unit unit;
public Project(final String id) {
this.id = id;
}
@Override
public String toString() {
return this.id + ": unit = " + this.unit.id;
}
}
Then we are ready to setup the map with a custom Comparator
:
final SortedMap<Project, List<Activity>> map = new TreeMap<>(new Comparator<Project>() {
@Override
public int compare(final Project p1, final Project p2) {
final int c = Integer.valueOf(p1.unit.id).compareTo(Integer.valueOf(p2.unit.id));
if (c != 0) {
return c;
}
return p1.id.compareTo(p2.id);
}
});
If we don't add id
to Project
and use it in the Comparator
, Project
instances with the same Unit.id
are considered to be equal.