2012-03-07 103 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(); 
    } 
}