[英]How to use a Java 8 Lambda expression to convert a List of one type to a List of its subtype
I can only seem to find how to do this in C# not Java. 我似乎只能在C#而不是Java中找到如何做到这一点。
I have a List<TypeX>
but I know that every single element in that list is actually a subclass of TypeX
Called TypeY
. 我有一个
List<TypeX>
但我知道该列表中的每个元素实际上都是TypeX
Called TypeY
的子类。
How can I write a Lambda expression that accepts List<TypeX>
and returns List<TypeY>
? 如何编写接受
List<TypeX>
并返回List<TypeY>
的Lambda表达式?
For my example, I will use the following classes: 对于我的例子,我将使用以下类:
class TypeX {}
class TypeY extends TypeX {}
Then I have a List<TypeX>
: 然后我有一个
List<TypeX>
:
final List<TypeX> xList = ...
All you need to do is use the a method reference to TypeY.class.cast
: 您需要做的就是使用
TypeY.class.cast
的方法引用:
final List<TypeY> yList = xList.stream()
.map(TypeY.class::cast)
.collect(toList());
You can also filter()
to exclude items that will cause an error: 您还可以
filter()
以排除将导致错误的项目:
final List<TypeY> yList = xList.stream()
.filter(TypeY.class::isInstance)
.map(TypeY.class::cast)
.collect(toList());
Examples use: 使用示例:
import static java.util.stream.Collectors.toList;
Just all map
with a lambda that casts the elements: 只是所有使用lambda的
map
都会强制转换元素:
List<TypeX> list = ...;
List<TypeY> castList =
list.stream().map(x -> (TypeY)x).collect(Collectors.toList());
You can use selectInstancesOf()
from Eclipse Collections : 您可以使用Eclipse Collections中的
selectInstancesOf()
:
MutableList<TypeX> xList = Lists.mutable.empty();
MutableList<TypeY> yList = xList.selectInstancesOf(TypeY.class);
If you can't change xList from List
: 如果您无法从
List
更改xList:
List<TypeX> xList = Lists.mutable.empty();
List<TypeY> yList = ListAdapter.adapt(xList).selectInstancesOf(TypeY.class);
Note: I am a contributor to Eclipse Collections. 注意:我是Eclipse Collections的贡献者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.