Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a list of Functions to a Java stream's .map() method

I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this:

List<NameValuePair> paramPairs = getParamPairs();
List<NameValuePair> newParamPairs = paramPairs.stream()
                .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp))
                .flatMap(Collection::stream)
                .collect(toList());

But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions. How would I do that?

like image 377
neu242 Avatar asked Jun 11 '15 11:06

neu242


1 Answers

If lookupFunction(nvp.getName()) returns a Collection of functions, you can get a Stream of that Collection and map each function to the result of applying it to the NameValuePair :

List<NameValuePair> newParamPairs = paramPairs.stream()
            .flatMap((NameValuePair nvp) -> lookupFunction(nvp.getName()).stream().map(func -> func.apply(nvp)))
            .flatMap(Collection::stream)
            .collect(toList());
like image 184
Eran Avatar answered Nov 14 '22 22:11

Eran