Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
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)