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.
You can use a Stream
with map
and collect
:
listB = listA.stream()
.map (a -> a*a)
.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