Start Coding Now

HashMap in Java - Key-Value Pairs

Learn about HashMap in Java. How to store items in "key/value" pairs and access them.

HashMap

A HashMap stores items in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value).

import java.util.HashMap;

public class Main { public static void main(String[] args) { HashMap capitalCities = new HashMap(); capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); System.out.println(capitalCities); // Access an item System.out.println(capitalCities.get("England")); } }

Frequently Asked Questions