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

4.1k Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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());
0
On

I'd use a function that composes the Collections of functions into one function. And use that instead of lookupFunction in my code

Function<String, Function<NameValuePair, NameValuePair>> composedFun = 
     x -> lookupFunctions(x)
             .stream()
             .reduce((fun1, fun2) -> fun1.andThen(fun2))
             .orElse(y -> y);
...
  .map(nvp -> composedFun.apply(nvp.getName()).apply(nvp))
...