如何从具有多种对象类型的集合中只读取一种类型的特定对象

How to read only specific objects of a type from a collection with multiple object types

我有一个包含两种对象类型的集合。我只想将两种类型中的一种读入一个新的 Set 中。 有没有一种优雅的方式来做到这一点?

就像 Suresh 所说的那样没有内置功能,这里有一些完整的代码:

for(Object obj : yourOldCollection) {
    if(obj instanceof SearchedType){
       yourNewSet.add(obj);
    }
}

使用 Google Guava 的过滤器。

Collections2.filter(yourOriginalCollection, new Predicate<Object>() {
    public boolean apply(Object obj) {
        return obj instanceof TypeYouAreInterestedIn;
    }
});

或在Java 8:

Collections2.filter(yourOriginalCollection, (obj) -> obj instanceof TypeYouAreInterestedIn);