简体   繁体   English

如何使用Java 8 Lambda表达式将一种类型的List转换为其子类型的List

[英]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;

Projecting in Java is done using the map method: 使用map方法在Java中进行投影:

List<TypeY> res = listTypeX
    .stream()
    .map((x) -> (TypeY)x)
    .collect(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM