I want to call a lambda function on each element of a List, and get the result in a new List.
My current version is this:
b = a.stream().map(i-> i+1).collect(Collectors.toList());
but it seems to be rather verbose and hides the intent of the code through all the boilerplate code that is needed for the transformation from list to stream and vice versa. The same code in other languages (e.g. ruby) would be much more concise, like below:
b = a.map{|i| i+1}
Of course one could do something like this:
for (int i: a) {
b.add(i+1);
}
but it looks a bit old-fashioned, and less flexible than the lambda version.
For mutating the existing List, Holger's comment list.replaceAll(i->i+1)
is good, but I am interested in creating a new List object.
Is there a consise way to call a lambda on each element of a list and create a new one with the result?
To get more concise, then you can use either some wrapper of the Stream API, or bypass it completely. You could implement something like:
class ListUtil {
public static <A, B> List<B> map(List<A> list, Function<? super A, ? extends B> f) {
List<B> newList = new ArrayList<>(list.size());
for(A a:list) {
newList.add(f.apply(a));
}
return newList;
}
}
Then with static imports, you can write:
b = map(a, i -> i + 1);
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