我需要的是以自定义方式订购列表,我正在寻找正确的方式并找到了番石榴的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();
您不需要番石榴,您所需的一切都在Collections API中。
假设AccountType工具Comparable,你可以只提供一个Comparator对于返回最小值"tfsa"和"rrsp",但叶选到其余AccountType的默认比较:
AccountType
Comparable
Comparator
"tfsa"
"rrsp"
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);
如果您不希望对其他项进行排序,只需提供一个默认比较器,该比较器始终返回0。