[英]Better way to create a stream of functions?
I wish to do lazy evaluation on a list of functions I've defined as follows; 我希望对我定义的函数列表进行惰性评估,如下所示;
Optional<Output> output = Stream.<Function<Input, Optional<Output>>> of(
classA::eval, classB::eval, classC::eval)
.map(f -> f.apply(input))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
where as you see, each class (a, b & c) has an Optional<Output> eval(Input in)
method defined. 如您所见,每个类(a,b和c)都定义了一个
Optional<Output> eval(Input in)
方法。 If I try to do 如果我尝试做
Stream.of(...)....
ignoring explicit type, it gives 它忽略了显式类型
T is not a functional interface
T不是功能界面
compilation error. 编译错误。 Not accepting functional interface type for
T
generic type in .of(T... values)
在
.of(T... values)
不接受T
泛型类型的功能接口类型
Is there a snappier way of creating a stream of these functions? 有没有更快捷的方法来创建这些功能的流? I hate to explicitly define
of
method with Function
and its in-out types. 我讨厌明确定义
of
与法Function
和它的IN-OUT类型。 Wouldn't it work in a more generic manner? 它不会以更通用的方式工作吗?
This issue stems from the topic of the following question; 这个问题源于以下问题的主题;
Lambda Expression and generic method Lambda表达式和通用方法
You can break it into two lines: 你可以把它分成两行:
Stream<Function<Input, Optional<Output>>> stream = Stream
.of(classA::eval, classB::eval, classC::eval);
Optional<Output> out = stream.map(f -> f.apply(input))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
or use casting: 或使用铸造:
Optional<Output> out = Stream.of(
(<Function<Input, Optional<Output>>>)classA::eval,
classB::eval,
classC::eval)
.map(f -> f.apply(input))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
but I don't think you can avoid specifying the type of the Stream
element - Function<Input, Optional<Output>>
- somewhere, since otherwise the compiler can't infer it from the method references. 但我不认为你可以避免指定
Stream
元素的类型 - Function<Input, Optional<Output>>
- 某处,否则编译器无法从方法引用中推断它。
There is a way that allows to omit the Function<Input, Optional<Output>>
type, but it's not necessarily an improvement 有一种方法可以省略
Function<Input, Optional<Output>>
类型,但它不一定是改进
Optional<Output> o =
Stream.concat(Stream.of(input).map(classA::eval),
Stream.concat(Stream.of(input).map(classB::eval),
Stream.of(input).map(classC::eval)))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
and it doesn't scale. 它不会扩展。
It seems, the best option is to wait for Java-9 where you can use 看来,最好的选择是等待Java-9,你可以使用它
Optional<Output> o = classA.eval(input)
.or(() -> classB.eval(input))
.or(() -> classC.eval(input));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.