What I need is to order a list in a custom way, I'm looking into the correct way and found guava's Ordering api but the thing is that the list I'm ordering is not always going to be the same, and I just need 2 fields to be at the top of the list, for example I have this:
List<AccountType> accountTypes = new ArrayList<>();
AccountType accountType = new AccountType();
accountType.type = "tfsa";
AccountType accountType2 = new AccountType();
accountType2.type = "rrsp";
AccountType accountType3 = new AccountType();
accountType3.type = "personal";
accountTypes.add(accountType3);
accountTypes.add(accountType2);
accountTypes.add(accountType);
//The order I might have is : ["personal", "rrsp", "tfsa"]
//The order I need is first "rrsp" then "tfsa" then anything else
I tried with a custom comparator and using Ordering in Guava library, something like this:
public static class SupportedAccountsComparator implements Comparator<AccountType> {
Ordering<String> ordering = Ordering.explicit(ImmutableList.of("rrsp", "tfsa"));
@Override
public int compare(AccountType o1, AccountType o2) {
return ordering.compare(o1.type, o2.type);
}
}
but it throws an exception because explicit ordering doesnt support other items that are not in the list you provided, is there a way to do a partial explicit ordering? something like:
Ordering.explicit(ImmutableList.of("rrsp", "tfsa")).anythingElseWhatever();
order
/priority
) inAccountType
that would be1
and2
for these two account types and0
for every other type? And then you'd define the ordering primarily based on that property.