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
If you’re looking for something very short, you could use jOOλ‘s Seq.ofType() like that:
EDIT: Well, when on JDK 6 or JDK 7, you can use Guava 20.0 and its
Iterables.filter
method like this:In case you don’t need your returned
List
s to me mutable, you can replaceLists.newArrayList
withImmutableList.copyOf
.There is no ready-to-go solution, but you can do the same thing in one line like this:
This is useful to make immediately clear that your method is filtering on compatible objects.