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>
?
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.
// 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.
The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters.
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 .
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With