[英]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 . 在Java8中我有一个流,我想应用一个映射器流 。
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
loop for
循环 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. 由于
map
需要一个可以应用于每个元素的Stream<Function<…>>
,但Stream<Function<…>>
只能进行一次计算,因此将流处理为可重用的东西是不可避免的。 If it shouldn't be a Collection
, just reduce it to a single Function
: 如果它不应该是
Collection
,只需将其减少为单个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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.