简体   繁体   中英

Need a very fast Java mechanism for iterating in random order through the entries in a Hashtable

I need a very fast mechanism for iterating in random order through the entries in a Hashtable. The number of entries in the table will typically be around 10 and will never be more than 20. Presently I'm doing the following code to randomize the order of the keys by picking 16 random, unique Doubles and sorting on that, but am thinking it isn't the most efficient solution:

    TreeMap<Double, String> seeds = new TreeMap<Double, String>();

    // These go in random order
    Enumeration<String> keys = content.keys();
    while (keys.hasMoreElements()) {
        String key = keys.nextElement();
        Double seedKey = new Double(Math.random());
        while (seeds.get(seedKey) != null)
            seedKey = new Double(Math.random());
        seeds.put(seedKey, key);
    }
    // Now enumerate through the seeds
    Set<Double> keys2 = seeds.keySet();
    for (Double d : keys2) {
        String key = seeds.get(d);
        String value = content.get( key );
        ..................

One suggestion I was given was to iterate over the key array from 0 to size-2 and swap element i with element random(from i+1 to size-1). It's linear at least. Looking forward to suggestions!

List<Map.Entry<Key, Value>> entries = new ArrayList<>(map.entrySet());
Collections.shuffle(entries);
for (Map.Entry<Key, Value> entry : entries) {
  // do whatever with entry.getKey(), entry.getValue()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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