集合removeAll方法 [英] Collections removeAll method

查看:157
本文介绍了集合removeAll方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道下列内容是否可行,

I would like to know if something like below is possible,

list.removeAll(namesToRemove)

我希望上下文是可以理解的。

I hope the context is understandable.

列表的类型为 ArrayList< MyObject> 其中 MyObject 有一个 getName 方法。

The list is of type ArrayList<MyObject> where MyObject has a getName method.

namesToRemove 是一个 ArrayList< String> ,包含要删除的对象的名称。

The namesToRemove is an ArrayList<String> containing names of the objects to be removed.

我知道这可以通过覆盖 MyObject 类中的equals方法来实现。我想知道是否存在任何其他选择。

I know this can be achieved by overriding equals method in MyObject class. I would like to know if any other choice is present.

推荐答案

你可以使用 Google Collections Collections2.filter()

You can do something like this using Google Collections Collections2.filter():

final List<String> namesToKeep = getNamesToFilter();
List<MyObject> filtered = Collections2.filter(originalList, new Predicate<MyObject>() {
  @Override
  public boolean apply(MyObject o) {
    return namesToKeep.contains(o.getName());
  }
});

这篇关于集合removeAll方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆