I have a list of objects of "Category" class:
public class Category {
private String originalId;
private Double ordinal;
private String sportId;
private String sportName;
private String type;
private String version;
}
And a list of objects of "League" class:
public class League {
private String leagueName;
private String originalId;
private int rank;
public League(String name, String originalId, int rank) {
this.leagueName = name;
this.originalId = originalId;
this.rank = rank;
}
These classes are describing the same entitities (so "originalId" field value of "Category" class is equal to "originalId" field value of "League" class), but values for them are taken from different sources, that's why they were separated from the beginning
What I need to do, is to sort a "Category" list by "rank" field value from "League" class
So, logic of sorting should be as following:
For each "Category" object, I will try to find a corresponding "League" object, by comparing their "originalId" field
if there is a corresponding object found, then take a value of "rank" field from "League" object and use it for sorting a list of "Category" objects by rank
if there is no corresponding object found, then such "Category" object should be moved to the end of a list during sorting
So, a comparator should be like this:
public static Comparator<Category> byRank() {
return nullsLast(comparing(Category::getRankFromCorrespondingLeagueObject, nullsLast(naturalOrder())));
}
And this is where I stumped, because it is unusual for me to use a field value, taken from another object, for using it while sorting
Is there some simple nice approach to doing so ?