I want to write the following code in a functional way with streams and lambdas:
Thing thing = new Thing();
List<Thing> things = new ArrayList<>();
things.add(thing);
for (int i = 0; i < 100; i++) {
thing = computeNextValue(thing);
things.add(thing);
}
Something in the way of this...
Supplier<Thing> initial = Thing::new;
List<Things> things = IntStream.range(0, 100).???(...).collect(toList());
List<Thing> things = Stream.iterate(new Thing(), t->computeNextValue(t))
.limit(100).collect(Collectors.toList());
You can also use a method reference for t->computeNextValue(t)
.
If computeNextValue
is a static
method replace t->computeNextValue(t)
with ContainingClass::computeNextValue
, otherwise use this::computeNextValue
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With