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 goin
Here's a Comparator
solution that uses a List
of strings to represent your sorting order. Change your sorting order by merely changing the order of the strings in your sortOrder
list.
Comparator<AccountType> accountTypeComparator = (at1, at2) -> {
List<String> sortOrder = Arrays.asList(
"rrsp",
"tfsa",
"third"
);
int i1 = sortOrder.contains(at1.type) ? sortOrder.indexOf(at1.type) : sortOrder.size();
int i2 = sortOrder.contains(at2.type) ? sortOrder.indexOf(at2.type) : sortOrder.size();
return i1 - i2;
};
accountTypes.sort(accountTypeComparator);
You don't need Guava for this, everything you need is in the Collections API.
Assuming AccountType
implements Comparable
, you can just provide a Comparator
that returns minimum values for "tfsa"
and "rrsp"
, but leaves the rest of the sorting to AccountType
's default comparator:
Comparator<AccountType> comparator = (o1, o2) -> {
if(Objects.equals(o1.type, "rrsp")) return -1;
else if(Objects.equals(o2.type, "rrsp")) return 1;
else if(Objects.equals(o1.type, "tfsa")) return -1;
else if(Objects.equals(o2.type, "tfsa")) return 1;
else return o1.compareTo(o2);
};
accountTypes.sort(comparator);
If you don't want your other items sorted, just provide a default comparator that always returns 0.