Java 8 Lambdas - 相当于c#OfType [英] Java 8 Lambdas - equivalent of c# OfType
问题描述
我现在正在学习新的Java 8功能,经过4年专门在C#世界,所以lambdas对我来说是最重要的。我现在正在努力找到C#的OfType方法的等价物。
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" method.
我所拥有的是一个List myNodes,我想从中得到一个List,其中Node是一个接口,而SpecificNode正在实现它。
What I have is a List myNodes , I want to get a List out of it, where Node is an interface, and SpecificNode is implementing it.
在C#中它将是
IList<INode> myNodes = new List<INodes>(){new SpecificNode(), new OtherNode()}
IList<SpecificNode> specificNodes = myNodes.OfType<SpecificNode>()
推荐答案
那里在 .OfType< T>()
方法中,没有完全匹配Java,但您可以使用Java8的过滤功能:
There is no exact match in Java for the .OfType<T>()
method, but you can use the Java8's filtering features:
IList<INode> myNodes = new ArrayList<INode>();
myNodes.add(new SpecificNode());
myNodes.add(new OtherNode());
List<SpecificNode> 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<SpecificNode> filteredList = myNodes.stream()
.filter(SpecificNode.class::isInstance)
.map(SpecificNode.class::cast)
.collect(Collectors.toList());
这篇关于Java 8 Lambdas - 相当于c#OfType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!