繁体   English   中英

在块中迭代一个hashmap'

[英]iterate through a hashmap 'in chunks'

我需要遍历一个包含5000个项目的hashmap,但是在迭代了第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<>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM