我有这样的东西:
public class Foo {
public String id;
}
和
Vector<Foo> foos;
我需要通过 id 从集合中获取一个对象。
在 C# 中我会这样做:foos.Where(o => o.id = 7)
在 Java 中执行此操作的最佳方法是什么?
最佳答案
首先,我建议使用 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 中。
关于Java 集合过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789701/