Maps

A Map 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). It can store different types: String keys and Integer values, or the same type, like: String keys and String values. There are many different types of maps however HashMaps are most commonly used.

Map Implementation Using Hash Functions

tbd

Maps In Java

Creating Map Objects

HashMaps can be created with the default constructor:

Map map = new HashMap();

Type-safe HashMaps can be defined in the following way:

Map<Obj, Obj> map = new HashMap<Obj, Obj> ();
Map<String, String> map = new HashMap<String, String> (); // creates an map with string keys and string values

Operations on Maps

The most important operations on Maps are:

  • Object put(Object key, Object value): Associates the specified value with the specified key
  • Object get(Object key): return the value to a given key
  • Object remove(Object key): Removes the mapping for a key from this map if it is present
  • int size(): Returns the number of key-value mappings in this map.

Working with Maps

The following java program demonstrates working with Maps:

// Create a HashMap object called capitalCities
Map<String, String> capitalCities = new HashMap<String, String>();

// Add keys and values (Country, City)
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
capitalCities.put("USA", "Washington DC");

System.out.println(capitalCities.size()); // outputs 3
System.out.println(capitalCities.get("England")); // outputs London
capitalCities.remove("Germany");
System.out.println(capitalCities.size()); // outputs 2

Loop through Maps

Loop through the items of a HashMap with a for-each loop. 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);
}

// Print values
for (String i : capitalCities.values()) {
  System.out.println(i);
}

Source:

results matching ""

    No results matching ""