繁体   English   中英

从列表中过滤特定类型

[英]Filtering specific type from list

怎么只给所有的狗?

在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");
    }

}

可能有更好的方法来执行此操作,但您可以使用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");
        }
    }

}

使用Guava和JDK集合,

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

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

   <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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM