我需要遍历具有5000个项目的哈希图,但是在第500个项目上进行迭代之后,我需要进行睡眠,然后继续下一个500个项目。这是从这里偷来的例子。任何帮助,将不胜感激。
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map 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
System.out.println("Total vehicles: " + vehicles.size());
// Iterate over all vehicles, using the keySet method.
// here are would like to do a sleep iterating through 500 keys
for(String key: vehicles.keySet())
System.out.println(key + " - " + vehicles.get(key));
System.out.println();
String searchKey = "Audi";
if(vehicles.containsKey(searchKey))
System.out.println("Found total " + vehicles.get(searchKey) + " "
+ searchKey + " cars!\n");
// Clear all values.
vehicles.clear();
// Equals to zero.
System.out.println("After clear operation, size: " + vehicles.size());
}
}
只需使用一个计数器变量即可跟踪到目前为止的迭代次数:
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.
}
}
请注意,如果您希望循环中同时包含键和值,则最好迭代地图的entrySet()
:
for(Map.Entry<String, Integer> entry: vehicles.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// ...
}
另外:不要使用原始类型:
Map<String, Integer> vehicles = new HashMap<>();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句