Ordering with partial explicit and then another order?

后端 未结 2 1444
Happy的楠姐
Happy的楠姐 2021-01-21 05:10

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

2条回答
  •  滥情空心
    2021-01-21 06:07

    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 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.

提交回复
热议问题