Java:仅从集合中选择所提供类型的元素 [英] Java: select from collection only elements of provided type
问题描述
我有一个类型B和C的元素的集合,所有扩展A.我需要过滤集合,以获取元素只有B类型。
I have a collection of elements of type B and C, which all extends A. I need to filter the collection to get elements of only B type.
有任何方法除外:
for (A a : initCollection) {
if (a instanceof B) {
newCollection.add(a)?
}
}
感谢
推荐答案
Guava 在其他答案中被提及,但不是特定的解决方案,这甚至比人们更容易实现:
Guava was alluded to in other answers, but not the specific solution, which is even simpler than people realize:
Iterable<B> onlyBs = Iterables.filter(initCollection, B.class);
这很简单,干净,做正确的事情,只创建一个实例,不会产生任何警告。
It's simple and clean, does the right thing, only creates a single instance and copies nothing, and doesn't cause any warnings.
( Collections2.filter()
,所以如果你真的想要一个 Collection
,你必须提供 Predicates.instanceOf(B.class)
和所得到的集合仍然可能是 Collection
类型。)
(The Collections2.filter()
method does not have this particular overload, though, so if you really want a Collection
, you'll have to provide Predicates.instanceOf(B.class)
and the resulting collection will still sadly be of type Collection<A>
.)
这篇关于Java:仅从集合中选择所提供类型的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!