Force a wait or sleep during stream

Viewed 1071

Let's say I have:

 list.stream()
     .map(someService::someRateLimitedApiCall) //does not implement Runnable
     .filter(Optional::isPresent)
     .map(Optional::get)
     .sleep(1000) //is something like this possible?
     .min...;

The API service only allows limited number of transactions per second, and I am seeking to introduce a delay in between calls.

If not, is there a way to add an executor with a fixed delay within the iteration of the stream?

(To be clear, I am not violating the terms of the external API and will not abuse the service.)

2 Answers

Rather than use peek, why not just put the delay in the map operation which calls the API?

.map(e -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        return Optional.empty();
    }
    return someRateLimitedApiCall(e);
})

The simple solution (without parallel streams) was to use peek as multiple commenters suggested. Since it requires a Consumer:

.peek(i -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
})
Related