skip to Main Content

I wonder if there is ready solution, that converts raw collection (List, Set etc.) to generic collection (List, Set etc.). I’ve wrote my own bicycle for it:

public <T> List<T> filterInstancesOfClass(List list, Class<T> clazz) {
    List<T> generifiedList = new ArrayList<T>();
    for (Object o : list) {
        if (clazz.isInstance(o)) {
            generifiedList.add(clazz.cast(o));
        }
    }
    return generifiedList;
}

But I’m sure, that there should be a ready solution somewhere in popular libraries, that work with collections (Apache, Guava). Do you know one?

UPD. Unfortunately I can’t use Java 8 in my case, so I’m looking for a ready solution outside JDK.

2

Answers


  1. If you’re looking for something very short, you could use jOOλ‘s Seq.ofType() like that:

    Seq.seq(list).ofType(clazz).toList()
    

    EDIT: Well, when on JDK 6 or JDK 7, you can use Guava 20.0 and its Iterables.filter method like this:

    public <T> List<T> filterInstancesOfClass(List<?> list, Class<T> clazz) {
        return Lists.newArrayList(Iterables.filter(list, clazz));
    }
    

    In case you don’t need your returned Lists to me mutable, you can replace Lists.newArrayList with ImmutableList.copyOf.

    Login or Signup to reply.
  2. There is no ready-to-go solution, but you can do the same thing in one line like this:

    public <T> List<T> filterInstancesOfClass(List<?> list, Class<T> clazz) {
        return list.stream().filter(p -> clazz.isInstance(p)).map(p -> clazz.cast(p)).collect(Collectors.toList());
    }
    

    This is useful to make immediately clear that your method is filtering on compatible objects.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search