I am learning the new java 8 features now, after 4 years exclusively in C# world, so lambdas are on top for me. I am now struggling to find an equivalent for C#\'s \"OfType\" me
I was having the same issue. This is what I came up with, but since java doesn't do extension methods (maybe in 10 more years?), it is a static method. This is using the stream API, though there isn't a particular reason you must do that. The same basic checks would work just fine in a for loop with a preallocated ArrayList.
@SuppressWarnings("unchecked")
private static List ofType(Class> out, List
Here is the version that doesn't use streams. It works just the same, but some of the fun with streams is that ... you might be able to stream them, if thats your kind of thing. I don't find it useful very often except for helpers like this.
private static List ofType(Class> out, List list) {
List outList = new ArrayList(list.size());
for(Object o : list) {
if ( out.isAssignableFrom(o.getClass())) {
outList.add((T)o);
}
}
return outList;
}