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
for
loopSince 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With