Java: HashMap
A HashMap
however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String
).
Create a HashMap
object called capitalCities that will store String
keys and String
values:
import java.util.HashMap; // import the HashMap class HashMap<String, String> capitalCities = new HashMap<String, String>();
Add Items
import java.util.HashMap; public class Main { 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); } } // Outputs: {USA=Washington DC, Norway=Oslo, England=London, Germany=Berlin}
Access an Item
capitalCities.get("England"); // Outputs: London
Remove an Item
capitalCities.remove("England");
To remove all items, use the clear()
method:
capitalCities.clear();
HashMap Size
capitalCities.size();
Loop Through a HashMap
Use the keySet()
method if you only want the keys, and use the values()
method if you only want the values:
// Print keys for (String i : capitalCities.keySet()) { System.out.println(i); } // Outputs: USA Norway England Germany
// Print values for (String i : capitalCities.values()) { System.out.println(i); } // Outputs: Washington DC Oslo London Berlin
// Print keys and values for (String i : capitalCities.keySet()) { System.out.println("key: " + i + " value: " + capitalCities.get(i)); } // Outputs: key: USA value: Washington DC key: Norway value: Oslo key: England value: London key: Germany value: Berlin