首页 > 解决方案 > Running a lambda in a loop

问题描述

I am creating an event by providing a Instant of time.

serviceContainer.consumeEvent(event ->
        event.setPayload(new TriggerCalculation(Instant.ofEpochMilli(serviceContainer.currentTimeMillis())
)));

However, I would like to add a fixed interval of time to the Instant and create a new event with the new Instant.

serviceContainer.consumeEvent(event ->
        event.setPayload(new TriggerCalculation(Instant.ofEpochMilli(serviceContainer.currentTimeMillis()).plus(1, ChronoUnit.DAYS)
        )));

However, I cannot do this in a for loop since index i needs to be final:

for(int i=1; i<7; i++){
    serviceContainer.consumeEvent(event ->
            event.setPayload(new TriggerCalculation(Instant.ofEpochMilli(serviceContainer.currentTimeMillis()).plus(i, ChronoUnit.DAYS)
            )));

}

How can loop a lambda in java if I want to increment a value within the lambda?

标签: javalambda

解决方案


你可以用IntStream.range这个

IntStream.range(0, 7)
            .forEach(i -> serviceContainer.consumeEvent(event ->
                    event.setPayload(new TriggerCalculation(Instant.ofEpochMilli(serviceContainer.currentTimeMillis()).plus(i, ChronoUnit.DAYS)
                    ))));

推荐阅读