This example shows how to get the value for a key from Java Hashtable using the get method and getOrDefault method.
How to get the value for a key from Hashtable using the get method?
The Hashtable get
method returns the value mapped to the specified key in the hashtable object.
1 |
public V get(Object key) |
It returns null if the specified key does not exist in the hashtable object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Hashtable; public class HsahtableGetValueExample { public static void main(String[] args) { Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); /* * To get a value mapped to the key, * use the get method */ //this will return "Two" i.e. value mapped to key 2 System.out.println( hashtable.get(2) ); //this will return null as the key 5 does not exist System.out.println( hashtable.get(5) ); } } |
Output
1 2 |
Two null |
How to get the value for a key from Hashtable using the getorDefault method?
As we can see from the previous output, the Hashtable get
method returns null if the specified key is not mapped to any value in the hash table object.
If you want to get a default value instead of a null if the key does not exist in the hash table object, then you can use the Hashtable getOrDefault
method.
1 |
public V getOrDefault(Object key, V defaultValue) |
The getOrDefault
method returns the value mapped to the given key if the key exists in the hashtable object. If the key does not exist, it returns the specified default value instead of a null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); /* * this will return "Two" i.e. value mapped to key 2 */ System.out.println( hashtable.getOrDefault(2, "DoesNotExist") ); /* * this will return "DoesNotExist" i.e. specified * default value as the key 5 does not exist */ System.out.println( hashtable.getOrDefault(5, "DoesNotExist") ); |
Output
1 2 |
Two DoesNotExist |
Important Note:
The Hashtable get
and getOrDefault
methods throw NullPointerException exception if the specified key is null. Unlike the HashMap class in Java, the Hashtable class does not allow null keys or values.
This example is a part of the Hashtable in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Hashtable Documentation