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
Instead of first filtering and then mapping the stream to the desired target type, it is possible to do both in a single call to the stream via flatMap
and this small helper function:
private static Function > ofType(Class targetType) {
return value -> targetType.isInstance(value) ? Stream.of(targetType.cast(value)) : Stream.empty();
}
This Function
basically checks for a element if a cast is possible and then casts it, returning a stream with the single casted element or an empty stream if the cast was not possible.
Stream.of(1, 2, 3, "Hallo", 4, 5, "Welt")
.flatMap(ofType(String.class))
.forEach(System.out::println);
With the help of a flatMap
operation all returned streams can be concatenated.
I assume that a separated check and cast are easier to understand and maybe even faster in execution, this is just a prove of concept for a single stream operation.