Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 idiomatic way to apply a Lambda to a List returning another List?

What's the most idiomatic mechanism to apply a lambda to every item in a list, returning a list made up of the results?

For example:

List<Integer> listA = ... imagine some initialization code here ...

List<Integer> listB = listA.apply(a -> a * a);   // pseudo-code (there is no "apply")

/* listB now contains the square of every value in listA */

I checked the API javadocs and also looked into Apache Commons, but didn't find anything.

like image 463
Alex R Avatar asked Oct 05 '14 17:10

Alex R


1 Answers

You can use a Stream with map and collect :

listB = listA.stream()
             .map (a -> a*a)
             .collect (Collectors.toList());
like image 168
Eran Avatar answered Oct 14 '22 18:10

Eran