在Java中按类获取子列表

时间:2012-07-08 11:05:02

标签: java list generics subclass

假设我有一个

ArrayList<Fruit>

我想从Fruit的任何给定子类的列表中获取所有元素,例如

ArrayList<Apple>

C#似乎有一个相当方便的

OfType<T>() 

方法。在Java中有没有相同的方法呢?

干杯

4 个答案:

答案 0 :(得分:5)

public static <T> Collection<T> ofType(Collection<? super T> col, Class<T> type) {
  final List<T> ret = new ArrayList<T>();
  for (Object o : col) if (type.isInstance(o)) ret.add((T)o);
  return ret;
}

答案 1 :(得分:2)

使用Guava,它只是

List<Apple> apples =
  Lists.newArrayList(Iterables.filter(fruitList, Apple.class));

(披露:我向Guava捐款。)

答案 2 :(得分:0)

List<Fruit> list=new ArrayList<Fruit>();
//put some data in list here
List<Apple> sublist=new ArrayList<Apple>();
for (Fruit f:list)
    if(f instanceof Apple)  
        sublist.add((Apple)f);

答案 3 :(得分:0)

我们创建了一个名为JLinq的小实用程序,以获得类似java中C#中的linq的功能,其中一个类似于typeof:

 /**
 * @param <T> the type of the list
 * @param list the list to filter
 * @param type the desired object type that we need from these list
 * @return a new list containing only those object that from the given type 
 */
public static <T> LinkedList<T> filter(LinkedList<T> list, Class<T> type) {
    LinkedList<T> filtered = new LinkedList<T>();
    for (T object : list) {
        if (object.getClass().isAssignableFrom(type)) {
            filtered.add(object);
        }
    }
    return filtered;
}