share

Thursday, 11 June 2015

How to create HashTable In Java

import java.util.Hashtable;

public class CreateHashTable {
   
public static void main(String[] args) {
   
    Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
   
    /*
     * Maps the specified key to the specified
     * value in this hashtable
     */
    ht.put(1, "java");
    ht.put(2, "jersey");
    ht.put(3, "spring");
    ht.put(4, "c");
    ht.put(5, "php");
   
    //print hashtable
    System.out.println("Hash Table is ="+ht);
     }   
}

Output:

Hash Table is ={5=php, 4=c, 3=spring, 2=jersey, 1=java}

2 comments:

  1. can you please suggest this code. I could not able to insert the values into the Datastax Cassandra Database.
    -------------------------------------------------
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.ServletException;
    import com.datastax.driver.core.BoundStatement;
    import com.datastax.driver.core.Cluster;
    import com.datastax.driver.core.Session;
    import com.datastax.driver.core.PreparedStatement;
    import java.lang.String;

    public class Register extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String i = request.getParameter("emp_id");
    String e = request.getParameter("emp_city");
    String n = request.getParameter("emp_name");
    String p = request.getParameter("emp_phone");
    String s = request.getParameter("emp_sal");

    try{
    //loading drivers for cassandra
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    //creating connection with the database
    Session session = cluster.connect("sample_demo");
    //return session;

    PreparedStatement ps = session.prepare
    ("insert into emp12(emp_id,emp_city,emp_name,emp_phone,emp_sal) values(?,?,?,?,?)");

    BoundStatement bs = new BoundStatement(ps);

    session.execute(bs.bind(255,320,"javaproficiency"));
    System.out.println("ok");
    bs.setString(1,i);
    bs.setString(2,e);
    bs.setString(3,n);
    bs.setString(4,p);
    bs.setString(5,s);



    // int obj=bs.executeUpdate();

    // if(obj>0)

    out.println("You are sucessfully registered");
    }
    catch(Exception se)
    {
    se.printStackTrace();

    }

    }
    }

    ReplyDelete
  2. Dear Friends,
    Normal when write the code using java its inserting into the Datastax Cassandra database successfully. But when I have written the code using Servlets application (Web application) as code written above code. Please check and correct it . Its very helpful to me. I am very thankful ..vinod.p.reddy@gmail.com
    Best Regards
    Vinod

    ReplyDelete