Lists or Iterables can be filtered easily using guavas filter(Iterable<?> unfiltered, Class<T> type). This operation performs two tasks: the list is filtered and transformed into a sequence of the given type T.
Quite often however I end up with Iterables<Something<?>>
and I want to get a subsequence of Iterables<Something<T>> for some specialized T.
It is clear, that Guava can't solve this problem out of the box due to type erasure: Something<T> does not provide any direct information about its T.
Lets say I have something like S<? extends Number>.
If I am able to define some predicate which tells me if S<?> may be casted to S<Double> I may use it as a filer:
<T extends Number> Predicate<S<?>> isOfType(Class<N> type) {...}
with:
Iterable<S<?>> numbers;
Iterable<S<?>> filtered = Iterable.filter(numbers, isOfType(Double.class));
This performs the task of filtering but it misses the transformation step. If I think my Predicate works well I may even think of casting:
Iterable<S<Double>> doubles = (Iterable<S<Double>>) filtered;
But this exposes some ugly cast operation.
As an alternative I may provide a Function<S<?>, S<Double>> to perform the cast.
In constrast to Class.cast() however it should not throw a ClassCastException b