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
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());