Java Hashtable - getOrDefault() Method
The java.util.Hashtable.getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
Syntax
public V getOrDefault(Object key, V defaultValue)
Here, V is the type of value maintained by the container.
Parameters
key |
Specify the key whose associated value is to be returned. |
defaultValue |
Specify the default mapping of the key. |
Return Value
Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
Exception
NA
Example:
In the example below, the java.util.Hashtable.getOrDefault() method returns the value to which the specified key is mapped in the given hashtable.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a hashtable Hashtable<Integer, String> Htable = new Hashtable<Integer, String>(); //populating hashtable Htable.put(101, "John"); Htable.put(102, "Marry"); Htable.put(103, "Kim"); Htable.put(104, "Jo"); Htable.put(105, "Sam"); //printing the value associated with //specified key of the hashtable System.out.println("key 101: " + Htable.getOrDefault(101, "Blank")); System.out.println("key 102: " + Htable.getOrDefault(102, "Blank")); System.out.println("key 104: " + Htable.getOrDefault(104, "Blank")); System.out.println("key 107: " + Htable.getOrDefault(107, "Blank")); } }
The output of the above code will be:
key 101: John key 102: Marry key 104: Jo key 107: Blank
❮ Java.util - Hashtable