先部分显式排序,然后再排序?

Eef*_*ret 3 java collections comparator guava

我需要的是以自定义方式订购列表,我正在研究正确的方式并找到番石榴的订购 api 但问题是我订购的列表并不总是相同的,我只需要2 个字段位于列表顶部,例如我有这个:

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
Run Code Online (Sandbox Code Playgroud)

我尝试使用自定义比较器并在 Guava 库中使用 Ordering,如下所示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但它抛出一个异常,因为显式排序不支持您提供的列表中没有的其他项目,有没有办法进行部分显式排序?就像是:

Ordering.explicit(ImmutableList.of("rrsp", "tfsa")).anythingElseWhatever();
Run Code Online (Sandbox Code Playgroud)

Mik*_*elF 5

您不需要为此使用 Guava,您需要的一切都在 Collections API 中。

假设AccountType工具Comparable,你可以只提供一个Comparator对于返回最小值"tfsa""rrsp",但叶选到其余AccountType的默认比较:

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);
Run Code Online (Sandbox Code Playgroud)

如果您不希望对其他项目进行排序,只需提供一个始终返回 0 的默认比较器。