Java HashMap: Create & Use Dictionaries

In Java, you can use a HashMap to create a dictionary, also known as a map or key-value pair. Here is an example of creating and using a dictionary.

  1. Create a HashMap object to represent a dictionary.
HashMap<String, Integer> dictionary = new HashMap<>();

In this example, the keys of the dictionary are of type String and the values are of type Integer.

  1. Add key-value pairs to the dictionary.
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
  1. Retrieve values from a dictionary.
int appleValue = dictionary.get("apple");
System.out.println("The value of 'apple' is: " + appleValue);
  1. Iterate through all key-value pairs in the dictionary.
for (Map.Entry<String, Integer> entry : dictionary.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}

This allows you to create a dictionary and use it to store and retrieve key-value pairs. Keep in mind that in Java, HashMap is an unordered data structure, if ordered dictionary is needed, you can use TreeMap.

bannerAds