如何从具有多个对象类型的集合中仅读取类型的特定对象

Scy*_*Scy 6 java object hashmap set hashset

我有一个包含两种对象类型的集合.我想只将两种类型之一读入一个新的Set.这样做有一种优雅的方式吗?

Ste*_*Kuo 5

使用Google Guava的过滤器.

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

或者在Java 8中:

Collections2.filter(yourOriginalCollection, (obj) -> obj instanceof TypeYouAreInterestedIn);
Run Code Online (Sandbox Code Playgroud)