从列表中过滤特定类型

时间:2012-03-07 01:52:05

标签: java

如何只让所有的狗?

在C#中,您可以使用animals.OfType<Dog>(),Java中是否有任何快捷方式?

private static void snoopDogs() {

    Animal[] animals = { new Dog("Greyhound"), new Cat("Lion"), new Dog("Japanese Spitz") };

    for(Dog x : animals) { 
        System.out.println("Come over here");
    }

}

3 个答案:

答案 0 :(得分:1)

可能有更好的方法,但您可以使用instanceof运算符:

private static void snoopDogs() {

    Animal[] animals = { new Dog("Greyhound"), new Cat("Lion"), new Dog("Japanese Spitz") };

    for(Animal a : animals) { 
        if( a instanceof Dog ) {
            System.out.println("Come over here");
        }
    }

}

答案 1 :(得分:1)

使用Guava和JDK集合

Iterable<Dog> dogs = Iterables.filter(animals, Dog.class);

答案 2 :(得分:0)

我认为它不支持开箱即用。但是,只需几行代码即可轻松添加:

   <T> List<T> ofType(List<? extends T> collection, Class<? extends T> clazz) {
        List<T> l = new LinkedList<T>(); 
        for (T t : collection) {
            Class<?> c = t.getClass(); 
            if (c.equals(clazz)) {
                l.add(t);
            }
        }
        return l;
    }

例如:

import java.util.*;

public class SubListByType {
    class Animal {
        String breed;

        Animal(String breed) {
            this.breed = breed;
        }

        String getBreed() {
            return breed;
        }
    }

    class Dog extends Animal {
        Dog(String breed) {
            super(breed);
        }
    }

    class Cat extends Animal {
        Cat(String breed) {
            super(breed);
        }
    }

    <T>  List<T> ofType(List<? extends T> collection, Class<? extends T> clazz) {
        List<T> l = new LinkedList<T>(); 
        for (T t : collection) {
            Class<?> c = t.getClass(); 
            if (c.equals(clazz)) {
                l.add(t);
            }
        }
        return l;
    }

    void snoopDogs() {
        Animal[] animals = { new Dog("Greyhound"), new Cat("Lion"), new Dog("Japanese Spitz") };

        for(Animal x : animals) {
            System.out.println(x.getClass().getCanonicalName() + '\t' + x.getBreed());
        }

        System.out.println();

        // LOOK HERE
        for (Animal x : ofType(Arrays.asList(animals), Dog.class)) {
            System.out.println(x.getClass().getCanonicalName() + '\t' + x.getBreed());
        }
    }

    public static void main(String[] args) {
        SubListByType s = new SubListByType(); 
        s.snoopDogs();
    }
}