Java Collection过滤

Omu*_*Omu 3 java collections

我有这样的事情:

public class Foo {
  public String id;
}
Run Code Online (Sandbox Code Playgroud)

Vector<Foo> foos;
Run Code Online (Sandbox Code Playgroud)

我需要通过id从集合中获取一个对象.

在C#中我会这样做: foos.Where(o => o.id = 7)

在Java中最好的方法是什么?

Jon*_*eet 11

首先,我建议使用ArrayList<Foo>而不是Vector<Foo>- ArrayList几乎总是优先考虑Vector.

使用Google Collections API,尤其是Iterables.filter.它现在非常笨重 - 你需要预先设置谓词,或者使用匿名内部类,因为缺少lambda表达式.此外,Java没有扩展方法,因此您将调用Iterables.filter(collection, predicate)而不是collection.filter(predicate).在Java 7中,这些都会稍微简化一下.

请注意,使用filter将找到Iterable<Foo>- 如果您只需要第一个匹配,请Iterables.find改为使用,这相当于Enumerable.First<T>(Func<T, bool>)LINQ.


nd.*_*nd. 6

使用Google Collections,即:

Lists.newArrayList(Iterables.filter(foos, new Predicate<Foo>() {
  public boolean apply(Foo input) {
    return input != null && "7".equals(input.id);
  }
}));
Run Code Online (Sandbox Code Playgroud)

Iterables.filter(和Collections2.filter,它也会这样做)为你提供了一个关于过滤集合的实时视图,就像seh的概念一样,但代码更少.为了再次创建一个列表,我将它传递给Google Collection的List实用程序类的newArrayList方法.

就像其他人一样,我强烈建议不要使用Vector作为声明.相反,尝试使用最通用的类​​型,例如List <Foo>甚至Collection <Foo>.此外,除非您需要Vector的同步功能,否则请使用ArrayList(或其他适合该问题的类型).


Kev*_*ion 5

您可能希望将数据存储在Map <Integer,Foo>而不是List <Foo>中.例如,TreeMap将按排序顺序保存所有内容.