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:
1 2 3 4 5 6 7 8 9 10 11 |
List<String> names = new ArrayList<>(); names.add("Thanh"); names.add("Khanh"); names.add("Tan"); List<String> namesUpper = new ArrayList<>(); for (String s : names) { namesUpper.add(s.toUpperCase()); } System.out.println(namesUpper.toString()); |
Result:
And now, if we rewrite this code using map() method of Stream object with Lambda Expression from Java 8:
1 2 3 4 5 6 7 8 9 |
List<String> names = new ArrayList<>(); names.add("Thanh"); names.add("Khanh"); names.add("Tan"); List<String> namesUppper = names.stream() .map(x -> x.toUpperCase()) .collect(Collectors.toList()); System.out.println(namesUppper); |
The result will be same:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.huongdanjava.javaexample; import java.util.Date; public class Student { private String name; private Date dateOfBirth; public Student(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } } |
Now, I can extract list of Student object into list of String object of student name as follows.
1 2 3 4 5 6 7 8 9 |
List<Student> students = Arrays.asList( new Student("Khanh"), new Student("Thanh"), new Student("Tan")); List<String> names = students.stream() .map(s -> s.getName()) .collect(Collectors.toList()); System.out.println(names); |
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:
Siba Sethy
This is not the conversion from one object to other object. This is about updating the value in same object.
Khanh Nguyen
Where is it updated @Siba?