Java 8 functionality: how to calculate a list of dependent object evolutions?

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 along the way ...

Supplier<Thing> initial = Thing::new;
List<Things> things = IntStream.range(0, 100).???(...).collect(toList());
+4
source share
1 answer
List<Thing> things = Stream.iterate(new Thing(), t->computeNextValue(t))
                           .limit(100).collect(Collectors.toList());

You can also use the method link for t->computeNextValue(t).

If computeNextValuethis is a method static, replace t->computeNextValue(t)with ContainingClass::computeNextValue, otherwise use this::computeNextValue.

+7
source

Source: https://habr.com/ru/post/1542288/


All Articles