I want to use the parallelism that Java 8 Stream
s provide, but I also need certain operations to be done in a specific order or else everything will break. The problem is that using a stream means that the code is now asynchronous [NOTE: THIS IS INCORRECT], and I can't figure out how to make something happen only when it's finished iterating over the whole set. [NOTE: THIS HAPPENS AUTOMATICALLY]
Right now, my code is as follows:
public void iterateOverMap(Map<String, String> m)
{
AtomicInteger count = new AtomicInteger(0);
m.keySet().stream().forEach((k) -> {
Object o = m.get(k);
// do stuff with o
count.incrementAndGet();
});
// spin up a new thread to check if the Stream is done
new Thread(() -> {
for (;;)
{
if (count.intValue() >= map.size())
break;
}
afterFinishedIterating();
}).start();
}
I don't like the idea of having to spin up a new thread or block the main thread just to keep track of this one thing, but I can't think of how else I could do it. Does anyone know a better alternative?
Thanks!