Convert an object into another type using Lambda Expression and Stream in Java

Since Java 8, we have ability to convert an object into another type by using map() method of Stream object with Lambda Expression. In this tutorial, I will show to you all some examples about it.

Note that, map() method is an intermediate operation in Stream, so we need more a terminal method to complete pipeline Stream. You can see more about Stream object here.

The first example, we can convert a List of String in lowercase to a List of String in uppercase using map() method.

Before Java 8, we can do that like below:

Result:

Convert an object into another type using Lambda Expression and Stream in Java

And now, if we rewrite this code using map() method of Stream object with Lambda Expression from Java 8:

The result will be same:

Convert an object into another type using Lambda Expression and Stream in Java


The second example, that is we can extract some information from the object to some other objects with map() method.

Example, I have a Student object like below:

Now, I can extract list of Student object into list of String object of student name as follows.

In this example, s variable present for a Student object and you can get name of all students then put it into a List object.

Result:

Convert an object into another type using Lambda Expression and Stream in Java

 

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment