Java 8 Lambdas - equivalent of c# OfType

后端 未结 4 1609
悲&欢浪女
悲&欢浪女 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:32

    You can create a Function containing the Stream pipeline, which reduces its invocation.

        Function,List> ofSub =
           bl -> bl.stream()
                   .filter(x -> x instanceof SpecificNode)
                   .map(n -> (SpecificNode) n)
                   .collect(Collectors.toList());
    

    For instance:

        for( SpecificNode s: ofSub.apply( myNodes ) ){
             //...
        }
    

提交回复
热议问题