slartidan
slartidan

Reputation: 21608

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

Upvotes: 5

Views: 247

Answers (1)

Holger
Holger

Reputation: 298599

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);

Upvotes: 8

Related Questions