简体   繁体   中英

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. If I try to do

Stream.of(...)....

ignoring explicit type, it gives

T is not a functional interface

compilation error. Not accepting functional interface type for T generic type in .of(T... values)


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. Wouldn't it work in a more generic manner?

This issue stems from the topic of the following question;
Lambda Expression and generic method

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.

There is a way that allows to omit the Function<Input, Optional<Output>> type, but it's not necessarily an improvement

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

Optional<Output> o = classA.eval(input)
           .or(() -> classB.eval(input))
           .or(() -> classC.eval(input));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM