Java Tutorials
Java Methods
Java Classes
Java File Handling
In the ArrayList
chapter, you learned that Arrays stores items as a ordered order, and you should access them by reference number (int
type). HashMap
however, save items with "key / value" pairs, and you can access them with another type indicator (eg a String
).
One item is used as a key (index) for another item (value). It can store different types: String
keys with Integer
values, or similar type, such as: Cord keys and cable values:
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>();
The HashMap
class has many useful features. For example, to add items to it, use the put()
method:
// Import the HashMap class
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);
}
}
To access value in HashMap
, use the get()
method and refer to its key:
capitalCities.get("England");
To remove an item, use the remove()
method and refer to the key:
capitalCities.remove("England");
To delete all items, use the clear()
method:
capitalCities.clear();
To find out how many items there are, use the size()
method:
capitalCities.size();
Loop through the items of a HashMap
with a for-each loop.
Note: Use the keySet()
method if you only want keys, and use the values()
method if you only want values:
// Print keys
for (String i : capitalCities.keySet()) {
System.out.println(i);
}
// Print values
for (String i : capitalCities.values()) {
System.out.println(i);
}
// Print keys and values
for (String i : capitalCities.keySet()) {
System.out.println("key: " + i + " value: " + capitalCities.get(i));
}
Keys and values in HashMap items actually. In the examples above, we used "String" items. Remember that String in Java is an object (not an old version). To use other types, such as int, you must specify an equal wrapper category: Integer
. For other classic types, use: Boolean
boolean, Character
for Character, Double
for double, etc:
Create a HashMap
object called people that will store String
keys and Integer
values:
// Import the HashMap class
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called people
HashMap<String, Integer> people = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
people.put("John", 32);
people.put("Steve", 30);
people.put("Angie", 33);
for (String i : people.keySet()) {
System.out.println("key: " + i + " value: " + people.get(i));
}
}
}