【发布时间】:2017-02-08 23:46:13
【问题描述】:
我需要以自定义方式订购列表,我正在研究正确的方式并找到了 guava 的 Ordering 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
我尝试使用自定义比较器并在 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);
}
}
但它会引发异常,因为显式排序不支持您提供的列表中没有的其他项目,有没有办法进行部分显式排序?类似:
Ordering.explicit(ImmutableList.of("rrsp", "tfsa")).anythingElseWhatever();
【问题讨论】:
-
如果您在
AccountType中只有一个属性 (order/priority),这两种帐户类型分别为1和2,其他所有帐户类型为0类型?然后您将主要根据该属性定义排序。
标签: java collections guava comparator