I have a Hashtable object with all the data in it. I have a value and want to get its key from the Hashtable object. I know its the reverse which we normally do - but is this possible? How :confused:
Thanks for your time.
Printable View
I have a Hashtable object with all the data in it. I have a value and want to get its key from the Hashtable object. I know its the reverse which we normally do - but is this possible? How :confused:
Thanks for your time.
Code:import java.util.*;
public class ExpTest {
public static void main(String[] args) {
Random seed = new Random();
int limit = 100;
String domain = "abcdefghizklmnopqrstuvwxyz";
// Arrange to save a random value for later lookup.
String randomValue = null;
int size = 10;
int randomIndex = seed.nextInt(size);
Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>();
for(int j = 0; j < size; j ++) {
Integer key = Integer.valueOf(seed.nextInt(limit));
int index = seed.nextInt(domain.length());
String value = String.valueOf(domain.charAt(index));
if(j == randomIndex) {
randomValue = value;
System.out.println("randomValue = " + randomValue);
}
hashTable.put(key, value);
}
// Check keySet and entrySet.
Set<Integer> keySet = hashTable.keySet();
System.out.println("keySet = " + keySet);
Set<Map.Entry<Integer, String>> entrySet = hashTable.entrySet();
System.out.println("entrySet = " + entrySet);
// Find the key corresponding to each occurrence of randomValue.
Enumeration keys = hashTable.keys();
while(keys.hasMoreElements()) {
Integer key = (Integer)keys.nextElement();
String value = (String)hashTable.get(key);
if(value.equals(randomValue)) {
System.out.printf("Found key: %d for randomValue: %s%n",
((Integer)key).intValue(), randomValue);
}
}
}
}