0

I would like to get the same as Stream.of, but lazy. I.e. I want to do the same as

Stream<MyClass> s = Stream.of(
   expression1(),
   expression2(),
   expression3(),
   ...
)

I can do

List<Supplier<MyClass>> s = Arrays.asList(
   ()->expression1(),
   ()->expression2(),
   ()->expression3(),
   ...
)

but can it be done with streams? Note that it would be duplication if suppliers are put into stream elements...

Dims
  • 47,675
  • 117
  • 331
  • 600
  • Did you consider `Stream.of(() -> expression1(), () -> expression2(), ... )` ? If yes, what's wrong with it? That would be a stream of suppliers which can lazily evaluated in the stream. For instance `Stream.of().map(Supplier::get).filter().findFirst()`. – Alexander Ivanchenko Dec 01 '22 at 13:41
  • 3
    Compare with https://stackoverflow.com/a/28833677/2711488 – Holger Dec 01 '22 at 13:50

1 Answers1

0

You can create a Stream<Supplier> using Stream.of() exactly in the same a stream of any other objects.

Stream<Supplier<MyClass>> s = Stream.of(
    () -> expression1(),
    () -> expression2(),
    () -> expression3()
);

Then these suppliers can lazily evaluated in the stream.

Example:

MyClass result = s.map(Supplier::get)
    .filter(someCondition)
    .findFirst()
    .orElseThrow();
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
  • There is no sense to use streams then. Streams are for lazyness themselves. If I introduce lazyness with supplier, then I don't need a stream. – Dims Dec 02 '22 at 10:54
  • @Dims Intermediate stream operations are lazy, that's true, but it doesn't mean that a *method invocation expressions* placed into a stream would become lazy (unless they wrapped with a *function*). `Stream.of()` is a regular static method and its arguments would be eagerly evaluated before its frame can be placed on top of the call stack (i.e. before `Stream.of()` can be executed). JVM should fire `expression()` before the stream would be created. If you `expressions` to be lazy - don't invoke the behavior, provide them as *Functions*, objects representing behavior. – Alexander Ivanchenko Dec 02 '22 at 11:53