Reputation: 21168
Let say I have such Hashtable:
Hashtable<Object, Object> test = new Hashtable<>();
test.put("t", 1);
test.put(2, "t123");
test.put(3, true);
How could I just return any value from it or get any key from this hash table without knowing any key or value? Should I just iterate it and get first value or maybe there is some simpler better way?
Upvotes: 1
Views: 2153
Reputation: 200206
You can't get a random element from a hashtable in O(1), but the most efficient way to do it in O(n) would be something like this:
int chosenIndex = (int) Math.random()*map.size();
i = 0;
for (Object v : map.values())
if (i++ == chosenIndex)
return v;
BTW never use the Hashtable
class, which is still around only for backwards compatibility. Use HashMap
.
Upvotes: 1
Reputation: 4712
If you meant "any":
test.keys().nextElement();
or
test.element().nextElement();
Upvotes: 1
Reputation: 14278
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(10, "ddsadas");
map.put(23, "sdss");
map.put(24, "sdss");
map.put(90, "sdss");
now random key generation O(N)
:
int size = map.keySet().size();
int index=(int)(Math.random() * size)+1;
System.out.println(index);
for(Integer i : map.keySet()){
if(index==1){
System.out.println(i);
break;
}
else{
index--;
}
}
You can achieve this in O(1)
by putting there set in to an array and generate a random number among the array index and just return the value in the index of array. This is o(1)
.
Upvotes: 1
Reputation: 19776
You can put all entries into a List and then use a random index to retrieve a random entry.
Hashtable<Object, Object> test = new Hashtable<Object, Object>();
test.put("t", 1);
test.put(2, "t123");
test.put(3, true);
List<Entry<Object, Object>> entries = new ArrayList<Entry<Object, Object>>(test.entrySet());
Random random = new Random();
Entry<Object, Object> randomEntry = entries.get(random.nextInt(entries.size()));
Object randomValue = randomEntry.getValue();
Object randomKey = randomEntry.getKey();
Upvotes: 1