我需要的是以自定义的方式排列列表,我正在研究正确的方法,并找到番石榴的排序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
我试图用一个自定义的比较,并使用排序,番石榴库中,这样的事情:
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);
}
}
但它会抛出一个异常,因为显式排序不支持不在你提供的列表中的其他项目,有没有办法做一个部分显式的o订货信?像这样:
Ordering.explicit(ImmutableList.of("rrsp", "tfsa")).anythingElseWhatever();
如果你刚在'AccountType'属性('order' /'priority'),这将是'1'和'2'这两个帐户类型和'0'每一个其他类型的?然后你会定义主要基于该属性的顺序。 –
[Guava:如何从列表和单个元素创建明确的排序?]可能的副本(http://stackoverflow.com/questions/14403114/guava-how-to-create-an-explicit-ordering-from -a-list-and-a-single-element) –