Sitemap

Stream Transformation: map(..) method

1 min readAug 21, 2023

--

map(..) method mainly used for data transformation.

it help us to map data from one form to other form.

 Stream<R> map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.

Function is FunctionalInterface that takes one input and returns another input.

String a[]={"Ram","Shyam","Mohan","BhanuPratap"};

Arrays.stream(a)
.map(x->x.length())
.forEach(System.out::println);

Result:

3 5 5 11
Press enter or click to view image in full size

You can simply replace the expression x->x.length() with your function.

Function<String,Integer> getStrLength=(x)->x.length();

String a[]={"Ram","Shyam","Mohan","BhanuPratap"};
Arrays.stream(a)
.map(getStrLength)

Let’s consider a use-case, we have an Employee List and we just want a list of All Employee name OR email ID THEN we can map Employee object to List of Names or List of emails.

Get Playwithjava’s stories in your inbox

Join Medium for free to get updates from this writer.

Get list of Names(using Lambda Expression)

List<EmployeeBean> empList=AppUtil.getEmpList();

List<String> empNameList=empList.stream()
.map(x->x.getName()).collect(Collectors.toList());

empNameList.forEach(System.out::println);


Result:
Krish
Marina
Saloni
Saloni
Saloni
Amir

getList of all emails(using Lambda Expression):

List<String> empEmailList=AppUtil.getEmpList()
.stream()
.map(x->x.getEmail()).collect(Collectors.toList());

empNameList.forEach(System.out::println);

Get list of Names(using Method Reference)

List<EmployeeBean> empList=AppUtil.getEmpList();

List<String> empNameList=empList.stream()
.map(EmployeeBean::getName).collect(Collectors.toList());

empNameList.forEach(System.out::println);


Result:
Krish
Marina
Saloni
Saloni
Saloni
Amir

--

--

Playwithjava
Playwithjava

Written by Playwithjava

I am a Software Techie having 10 yrs of experience in product development