Java 8 Lambdas - equivalent of c# OfType

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

    There is no exact match in Java for the .OfType() method, but you can use the Java8's filtering features:

    IList myNodes = new ArrayList();
    myNodes.add(new SpecificNode());
    myNodes.add(new OtherNode());
    
    List filteredList = myNodes.stream()
                                             .filter(x -> x instanceof SpecificNode)
                                             .map(n -> (SpecificNode) n)
                                             .collect(Collectors.toList());
    

    If you want to get of the explicit cast, you can do:

    List filteredList = myNodes.stream()
                                                 .filter(SpecificNode.class::isInstance)
                                                 .map(SpecificNode.class::cast)
                                                 .collect(Collectors.toList());
    

提交回复
热议问题