2012-03-07 87 views
0

如何获取所有狗只?从列表中过滤特定类型

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

} 

回答

1

使用Guava和JDK集合,

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

谢谢,只需要使用'Arrays.asList'因此它可以是可迭代。虽然Iterables看起来并不像C#的OfType那样快捷,但无论如何都可以作为单线程来使用:-)(Dog d:Iterables.filter(Arrays.asList(animals),Dog.class)){ – Hao 2012-03-07 02:44:36

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

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