Dictionary size() Method in Java with Examples

The size() Method of Dictionary class in Java is used to know the size of the dictionary or the number of distinct keys present in the dictionary.

Syntax:

DICTIONARY.size()

Parameters:
The method does not accept any parameters.

Return Value:
The method returns the number of keys present in the dictionary.

Below programs illustrate the size() Method of Dictionary:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to illustrate size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // Creating a dictionary of Hashtable
        Dictionary<Integer, String> dict
            = new Hashtable<Integer, String>();
  
        // Inserting elements into the Dictionary
        dict.put(10, "Geeks");
        dict.put(15, "4");
        dict.put(10, "Geeks");
        dict.put(25, "Welcomes");
        dict.put(30, "You");
  
        // Displaying the Dictionary
        System.out.println("Dictionary: " + dict);
  
        // Displaying the size of the dictionary
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}

chevron_right


Output:

Dictionary: {10=Geeks, 30=You, 15=4, 25=Welcomes}
The size of the dictionary is 4

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code to illustrate size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // Creating a dictionary of Hashtable
        Dictionary<String, Integer> dict
            = new Hashtable<String, Integer>();
  
        // Inserting elements into the table
        dict.put("Geek", 10);
        dict.put("4", 15);
        dict.put("Geeks", 20);
        dict.put("Welcomes", 25);
        dict.put("You", 30);
  
        // Displaying the Dictionary
        System.out.println("Dictionary: " + dict);
  
        // Displaying the size of the dictionary
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}

chevron_right


Output:

Dictionary: {You=30, Welcomes=25, 4=15, Geeks=20, Geek=10}
The size of the dictionary is 5


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.