mappers = Stre-6ren">
gpt4 book ai didi

java - 将映射器流应用于 Java8 中的另一个流

转载 作者:搜寻专家 更新时间:2023-10-31 19:37:40 24 4
gpt4 key购买 nike

在 Java8 中,我有一个流,我想应用一个映射器流

例如:

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

我想写:

strings.map(mappers); // not working

但我目前解决任务的最佳方法是:

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

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

我该如何解决这个问题

  • 无需将映射器收集到列表中
  • 不使用for 循环
  • 不会破坏我流畅的代码

最佳答案

map需要一个可以应用于每个元素的函数,但是你的 Stream<Function<…>>只能评估一次,将流处理为可重用的东西是不可避免的。如果它不应该是 Collection , 只需将其缩减为单个 Function :

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

完整示例:

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

关于java - 将映射器流应用于 Java8 中的另一个流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com