0

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?

2
  • Assign i to another variable in the line before and use that in the lambda. Commented Jul 24, 2018 at 4:25
  • 1
    You can make a final TriggerCalculation outside of the lambda Commented Jul 24, 2018 at 4:26

3 Answers 3

2

You can use IntStream.range for this

IntStream.range(0, 7)
            .forEach(i -> serviceContainer.consumeEvent(event ->
                    event.setPayload(new TriggerCalculation(Instant.ofEpochMilli(serviceContainer.currentTimeMillis()).plus(i, ChronoUnit.DAYS)
                    ))));
Sign up to request clarification or add additional context in comments.

Comments

2

Move the integer out of the lambda

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

Comments

1

You can do something like this:

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

}

Or this:

IntStream.range(0, 7)
    .mapToObj(x -> Instant.ofEpochMilli(serviceContainer.currentTimeMillis()).plus(x, ChronoUnit.DAYS))
    .map(TriggerCalculation::new)
    .forEach(x -> {
        serviceContainer.consumeEvent(event ->
            event.setPayload(x));
    });

2 Comments

Is there a reason why the IntStream.range, suggested below, is not preferred?
@SSF You could argue that streams have some overheads, but not using them might be a micro-optimisation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.