Hatefiend :
I want to loop over a huge array and do a complicated set of instructions that takes a long time. However, if more than 30 seconds have passed, I want it to give up.
ex.
final long start = System.currentTimeMillis();
myDataStructure.stream()
.while(() -> System.currentTimeMillis() <= start + 30000)
.forEach(e ->
{
...
});
I want to avoid just saying return
inside the forEach
call if a certain condition is met.
SpaceTrucker :
If iterating the stream or array in this case is cheap compared to actually executing the operation than just use a predicate and filter whether time is over or not.
final long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(30L);
myDataStructure.stream()
.filter(e -> System.nanoTime() <= end)
.forEach(e ->
{
...
});
Question is if you need to know which elements have been processed or not. With the above you have to inspect whether a side effect took place for a specific element afterwards.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=429484&siteId=1