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).
One object is used as a key (index) to another object (value). It can store different types: String keys and Integer values, or the same type, like: String keys and String values:
Create a HashMap
object called capitalCities that will store String
keys and String
values:
Example
import java.util.HashMap; // import the HashMap class HashMapcapitalCities = new HashMap();
Add Items
The HashMap
class has many useful methods. For example, to add items to it, use the put()
method:
Example
// Import the HashMap class import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap object called capitalCities HashMapcapitalCities =new HashMap(); // 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
To access a value in the To remove an item, use the To find out how many items there are, use the Loop through the items of a Note: Use the Create a get()
method and refer to its key:
Example
capitalCities.get("England");
Remove an Item
remove()
method and refer to the key:Example
capitalCities.remove("England");
HashMap Size
size()
method:Example
capitalCities.size();
Loop Through a HashMap
HashMap
with a for-each loopkeySet()
method if you only want the keys, and use the values()
method if you only want the values:
HashMap
object called capitalCities that will store String
keys and String
values:Example
import java.util.HashMap; // import the HashMap class
HashMap