Hackerss.com

hackerss
hackerss

Posted on

Create a hashmap and fill it with values and print in Java

Create a hashmap and fill it with values and print - Java:


import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
   /**
   * This method create a hashmap and fill it with values and print with javadoc.
   * @param args Unused.
   * @return Nothing.
   */   
   public static void main(String[] args) {
      // Create a HashMap object called capitalCities
      HashMap<String, String> capitalCities = new HashMap<String, String>();

      // Add keys and values (Country, City)
      capitalCities.put("England", "London");
      capitalCities.put("Germany", "Berlin");
      capitalCities.put("Norway", "Oslo");
      capitalCities.put("USA", "Washington DC");

      System.out.println(capitalCities);

      // Access an item from the HashMap
      System.out.println(capitalCities.get("England"));

      // Remove an item from the HashMap
      capitalCities.remove("England");

      // Print the HashMap again to see the result
      System.out.println(capitalCities);

      // Iterate through a HashMap
      for (Map.Entry<String, String> entry : capitalCities.entrySet()) {
         System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
      }

   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)