Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a lambda on each element of a list and get the result in a new list? My working version is too verbose

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?

like image 986
user000001 Avatar asked Dec 11 '22 09:12

user000001


1 Answers

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);
like image 96
fgb Avatar answered Jan 30 '23 23:01

fgb