I need to iterate through a HashMap with 5000 items. After iterating on the 500th item, I need to do a sleep and then continue to the next 500 items.
Here is an example based on Java Map Example from Java Code Geeks:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> vehicles = new HashMap<>();
// Add some vehicles.
vehicles.put("BMW", 5);
vehicles.put("Mercedes", 3);
vehicles.put("Audi", 4);
vehicles.put("Ford", 10);
// add total of 5000 vehicles
// Iterate over all vehicles, using the keySet method.
// Here I would like to do a sleep after iterating through 500 keys
for(String key: vehicles.keySet())
System.out.println(key + " - " + vehicles.get(key));
}
}
Just have a counter variable to keep track of the number of iterations so far:
int cnt = 0;
for(String key: vehicles.keySet()) {
System.out.println(key + " - " + vehicles.get(key));
if (++cnt % 500 == 0) {
Thread.sleep(sleepTime); // throws InterruptedException; needs to be handled.
}
}
Note that if you want both key and value in a loop, it is better to iterate the map's entrySet():
for(Map.Entry<String, Integer> entry: vehicles.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// ...
}