Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through a hashmap 'in chunks'

Tags:

java

I need to iterate through a hashmap with 5000 items but after iterating on 500th item I need to do a sleep and then continue the next 500 items. Here is the example stolen from here. Any help would appreciated.

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()); 
    }
}
like image 665
PHA Avatar asked Aug 18 '16 14:08

PHA


People also ask

Can you iterate through a HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.

How many ways we can iterate HashMap in Java?

There are generally five ways of iterating over a Map in Java.

How do you iterate over a HashMap in Rust?

This is possible because HashMap , and &HashMap implements IntoIterator . If you're only interested in their names you would use ages. keys(), if you're only interested in their ages you would use ages.


1 Answers

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();
  // ...
}

Also: don't use raw types:

Map<String, Integer> vehicles = new HashMap<>();
like image 157
Andy Turner Avatar answered Oct 17 '22 00:10

Andy Turner