Java retainAll基于Enum值

时间:2012-09-09 07:31:14

标签: java enums

我有一个对象列表,它们都有一个名为AssetType的枚举值,是否可以使用retainAll()方法对列表进行排序,以便只保留包含AssetType.BANK_ACCOUNT的对象?

提前获取任何帮助。

2 个答案:

答案 0 :(得分:1)

如果您拉入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;
    }
}

答案 1 :(得分:1)

(披露:我向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();
  }
}