我有一个对象列表,它们都有一个名为 AssetType 的枚举值,是否可以使用 retainAll() 方法对列表进行排序,以便只保留具有 AssetType.BANK_ACCOUNT 的对象?
提前谢谢任何帮助。
如果您拉入Guava
,您可以在对象和它的 之间进行实时转换AssetType
,然后调用retainAll
它:
Lists.transform(allAssets, assetTypeFn).retainAll(
Collections.singleton(AssetType.BANK_ACCOUNT));
//...elsewhere...
public static final Function<MyObject, AssetType> assetTypeFn =
new Function<MyObject, AssetType>() {
public AssetType apply(MyObject object) {
return object.getAssetType();
}
};
filter()
同样,如果您不想更改原始列表,可以使用该方法:
List<MyObject> bankAccounts = Lists.newArrayList(
Iterables.filter(allAssets, isBankAccount));
public static final Predicate<MyObject> isBankAccount = new Predicate<MyObject>() {
public boolean apply(MyObject asset) {
return asset.getAssetType() == AssetType.BANK_ACCOUNT;
}
}
(披露:我为 Guava 做出了贡献。)
一个更直观的基于 Guava 的实现将是
Iterables.removeIf(allAssets, new Predicate<MyObject>() {
public boolean apply(MyObject asset) {
return asset.getAssetType() != AssetType.BANK_ACCOUNT;
}
});
...也就是说,老实说,我更喜欢愚蠢的纯 Java 实现:
Iterator<MyObject> itr = allAssets.iterator();
while (itr.hasNext()) {
if (itr.next().getAssetType() != AssetType.BANK_ACCOUNT) {
itr.remove();
}
}