Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Java 8 Lambda expression to convert a List of one type to a List of its subtype

Tags:

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>?

like image 412
Omar Kooheji Avatar asked Mar 25 '16 17:03

Omar Kooheji


People also ask

What is the return type of lambda expression in Java 8?

What is the return type of lambda expression? Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. 4.

How do I print a list in lambda expression?

// Create a list from a String array List list = new ArrayList(); String[] strArr = { "Chris", "Raju", "Jacky" }; for( int i = 0; i < strArr. length; i++ ) { list. add( strArr[i]); } // // Print the key and value of Map using Lambda expression // list. forEach((value) -> {System.

Can lambda expression contain data type?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters.

Is lambda expressions introduced in Java 8?

Introduction. Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .


2 Answers

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;
like image 86
Boris the Spider Avatar answered Oct 02 '22 04:10

Boris the Spider


Projecting in Java is done using the map method:

List<TypeY> res = listTypeX
    .stream()
    .map((x) -> (TypeY)x)
    .collect(Collectors.toList());
like image 40
Sergey Kalinichenko Avatar answered Oct 02 '22 03:10

Sergey Kalinichenko