I can only seem to find how to do this in C# not Java.
I have a List<TypeX>
but I know that every single element in that list is actually a subclass of TypeX
Called TypeY
.
How can I write a Lambda expression that accepts List<TypeX>
and returns List<TypeY>
?
For my example, I will use the following classes:
class TypeX {}
class TypeY extends TypeX {}
Then I have a List<TypeX>
:
final List<TypeX> xList = ...
All you need to do is use the a method reference to 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:
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:
List<TypeY> res = listTypeX
.stream()
.map((x) -> (TypeY)x)
.collect(Collectors.toList());
Just all map
with a lambda that casts the elements:
List<TypeX> list = ...;
List<TypeY> castList =
list.stream().map(x -> (TypeY)x).collect(Collectors.toList());
You can use selectInstancesOf()
from Eclipse Collections :
MutableList<TypeX> xList = Lists.mutable.empty();
MutableList<TypeY> yList = xList.selectInstancesOf(TypeY.class);
If you can't change xList from List
:
List<TypeX> xList = Lists.mutable.empty();
List<TypeY> yList = ListAdapter.adapt(xList).selectInstancesOf(TypeY.class);
Note: I am a contributor to Eclipse Collections.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.