Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 functional: How to compute a list of dependent evolutions of an object?

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());
like image 784
Philipp Jardas Avatar asked Mar 20 '23 11:03

Philipp Jardas


1 Answers

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.

like image 130
Holger Avatar answered Apr 25 '23 11:04

Holger