how to concat a string to an element of a HashTable using collection in java
Previous | Home | Next |
In this example we shall see how to concat a string to an existing element of the Hashtable.
For creating a Hashtable first of all we have to import the java.util package in which the java.util.Hashtable class is defined. In this example we have created a class named CollectionExample in which we have created a Hashtable and added some elements to it.
In this example we have used the concat() method for concating some string to the element of the Hashtable. The syntax of the concat() method is ,
String concat(String str)
This method concatenates the specified string to the current string object and returns the concatenated string as a result.
In this example we have created a Hashtable and then added some elements to it by using the put(Object key, Object value) method on the Hashtable object i.e ht(in our example). Then we have displayed the key and values of the Hashtable using for loop. For using the concat() method, firstly we have get the desired element to be concatenated and then we have concated our string to that element, this is done by the following line in our example,ht.get(i).concat(": software developer@r4r");
In this statment we have get the value at the index i, and then concatenate the "sofware developer@r4r" to it.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args) throws NullPointerException
{
// TODO Auto-generated method stub
try
{
Hashtable<Integer,String> ht=new Hashtable<Integer,String>(); // created a Hashtable named ht in which key is numeric and value is String types
ht.put(1, "r4r"); // adding the values to the hashtable using key-value pairs
ht.put(2, "development");
ht.put(3, "tutorials");
ht.put(4, "shashi");
ht.put(5, "software developer");
System.out.println("The size of the Hashtable ht is: "+ht.size()); // displaying the size of the Hashtable
System.out.println("The elements according to key are: ");
for(int i=1;i<=ht.size();i++)
{
System.out.println("key = "+i+","+"Value = "+ ht.get(i)); // displaying the key-value pair contained in the Hashtable
}
for(int i=1; i<=ht.size();i++)
{
if(ht.get(i).equalsIgnoreCase("shashi")) // checking if the at key i whether the element is shashi
{
System.out.println(ht.get(i).concat(": software developer@r4r")); // if so, then concatenated the given string to that element and displays it
}
}
}
catch(NullPointerException e) // handling the NullPointer Exception which is thrown
{
e.printStackTrace();
}
}
}
The output of the above example is as follows:
The size of the Hashtable ht is: 5
The elements according to key are:
key = 1,Value = r4r
key = 2,Value = development
key = 3,Value = tutorials
key = 4,Value = shashi
key = 5,Value = software developer
shashi: software developer@r4r
Previous | Home | Next |