Thursday, 10 December 2015

How to Search key/value in Hashtable?

package com.JavaInterview.Programs;

import java.util.Hashtable;
import java.util.Map;
import java.util.Scanner;


/**
 * Search key/value Hashtable
 * 
 * 
 */
public class HashtableKeySearch {

 public static void main(String args[]) {
  // Create Hashtable Instance
  Hashtable<Integer, String> JipHT = new Hashtable<Integer, String>();
  // Adding element to Hashtable
  JipHT.put(1, "first");
  JipHT.put(2, "second");
  JipHT.put(3, "third");

  // Print the Hashtable
  System.out.println("Original Hashtable :" + JipHT);

  Scanner input = new Scanner(System.in);
  // Search element by Key
  System.out.println("Please enter the key that you want to search :");
  int key = input.nextInt();

  if (JipHT.containsKey(key)) {
   System.out.println("The Hashtable contains the key " + key + " with value : " + JipHT.get(key));
  } else {
   System.out.println("The Hashtable dosn't contains the key");

  }
  // Search Element by Value
  Scanner input1 = new Scanner(System.in);
  Integer key1 = null;
  System.out.println("Please enter the value that you want to search :");
  String str = input1.next();
  for (Map.Entry entry : JipHT.entrySet()) {
   if (str.equals(entry.getValue())) {
    key1 = (Integer) entry.getKey();
    break;
   }
  }

  System.out.println("The key value from Hashtable for value " + str + "is :" + key1);
  input.close();
  input1.close();
 }
}

Output :
Original Hashtable :{3=third, 2=second, 1=first}
Please enter the key that you want to search :
3
The Hashtable contains the key 3 with value : third
Please enter the value that you want to search :
first
The key value from Hashtable for value firstis :1

No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...