Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a stream of mappers to another stream in Java8

In Java8 I have a stream and I want to apply a stream of mappers.

For example:

Stream<String> strings = Stream.of("hello", "world");
Stream<Function<String, String>> mappers = Stream.of(t -> t+"?", t -> t+"!", t -> t+"?");

I want to write:

strings.map(mappers); // not working

But my current best way of solving my task is:

for (Function<String, String> mapper : mappers.collect(Collectors.toList()))
    strings = strings.map(mapper);

strings.forEach(System.out::println);

How can I solve this problem

  • without collecting the mappers into a list
  • without using a for loop
  • without breaking my fluent code
like image 800
slartidan Avatar asked Nov 03 '15 19:11

slartidan


1 Answers

Since map requires a function that can be applied to each element, but your Stream<Function<…>> can only be evaluated a single time, it is unavoidable to process the stream to something reusable. If it shouldn’t be a Collection, just reduce it to a single Function:

strings.map(mappers.reduce(Function::andThen).orElse(Function.identity()))

Complete example:

Stream<Function<String, String>> mappers = Stream.of(t -> t+"?", t -> t+"!", t -> t+"?");
Stream.of("hello", "world")
      .map(mappers.reduce(Function::andThen).orElse(Function.identity()))
      .forEach(System.out::println);
like image 85
Holger Avatar answered Oct 25 '22 15:10

Holger