Java 8 Lambdas - equivalent of c# OfType

后端 未结 4 1612
悲&欢浪女
悲&欢浪女 2021-02-19 14:52

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

4条回答
  •  面向向阳花
    2021-02-19 15:25

    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.

提交回复
热议问题