Java Hashtable class implements a hash table, which maps keys to values. It inherits Dictionary class and implements the Map interface. Any non-null object can be used as a key or as a value. In this post, we will see “How to create a HashTable in Java and how to iterate its data using Set with an example?”
Key points to notice
- HashTable is similar to Java HashMap but is synchronized.
- HashTable stores key/value pair in a hash table.
- HashTable class contains unique elements.
- HashTable class doesn’t allow null key or value.
Syntax:
1 | Hashtable<String, String> table = new Hashtable<>(); |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Hashtable; import java.util.Set; public class HashTableExample { public static void main(String[] args) { Hashtable<String, String> hashTable = new Hashtable<>(); hashTable.put("name", "yogi"); hashTable.put("id", "100"); hashTable.put("age", "6"); hashTable.put("age", "7"); Set<String> keys = hashTable.keySet(); for(String key : keys){ System.out.println(key + " : "+ hashTable.get(key)); } } } |
Output:
1 2 3 | age : 7 name : yogi id : 100 |
Note: Previous value of key ‘age’ i.e ‘6’ in the above example is replaced with the new value i.e ‘7’.
Simplest representation of Hashtable in Java with example... Check it out...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams