Results 1 to 2 of 2
  1. #1
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

    Default Getting key from Hashable

    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.
    Last edited by ravian; 11-20-2007 at 10:54 AM.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java 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);
                }
            }
        }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •