Java programming course: 11.3 Maps

In the previous lesson we used our Pen class in ZooAdministrator.


Maps

 You can think of a Map as being like a dictionary – you can look up a word to find its definition. But maps in Java are much more flexible than that since you can use them to look up any object to find another object which is associated to it. The object you search for is known as the key, and the object that is associated with it is known as the value. Because a map can contain many items you can think of it as being a collection of pairs of keys and their associated values.

So that you can see a simple example to start with, here is a map which you can use to translate English words into French:

// Create a Map: key is English word, value is French word
Map<String, String> dictionary = new HashMap<>();
        
// Add some words to the dictionary
dictionary.put("yes", "oui");
dictionary.put("no", "non");
dictionary.put("hello", "bonjour");
dictionary.put("goodbye", "au revoir");
 
  • You declare a Map by specifying the formal type parameters of the key and value inside angle-brackets, which in this case is String for both (the first String relates to the type for the key and the second String relates to the type for the associated value)
  • Map is an interface, so you need to instantiate a class which implements it. There are two main choices: HashMap (which is unsorted) and TreeMap (which is sorted by the key). Because there is no current need to sort the items you will use HashMap
  • The put() method is used to place a pair of items into the map, where the first argument is the key and the second argument is the associated value. If you use put() using a key that is already in the map then it will replace the existing entry. There is a corresponding remove() method which removes an entry pair where you specify the key

To retrieve an item from a map you use the get() method passing a key:

// What is the French for hello?
System.out.println("The French for hello is " + dictionary.get("hello"));
 

If you want to iterate over a map, you can use a for-each loop, but you need to specify whether you want to iterate over the keys or the values. Iterating over the keys is more common, since you can then use the get() method inside the loop to get each associated value:

// Output the dictionary
for (String englishWord : dictionary.keySet()) {
    String frenchWord = dictionary.get(englishWord);
    System.out.println("The English word " + englishWord +
                    " is " + frenchWord + " in French.");
}
 
  • The keySet() method is used to tell the loop to use the keys to iterate over
  • Inside the loop, the get() method retrieves the value associated with the current key

To iterate over the values, specify values() in place of keySet():

// Output the French words
for (String frenchWord : dictionary.values()) {
    System.out.println(frenchWord);
}
 

If you want the map to be sorted on its keys you can simply change the instantiation of the dictionary map from HashMap to TreeMap:

Map<String, String> dictionary = new TreeMap<>(); 

It is also possible to convert an unsorted map into a sorted map by passing the unsorted map as an argument to a new map object, similar to how you converted an unsorted set. Therefore, instead of changing dictionary to TreeMap as above, you could keep it as a HashMap and then do this:

Map<String, String> sortedDictionary = new TreeMap<>(dictionary);
 

If you need to sort the values as opposed to the keys, then you can use the values() method to return a Collection and then pass that collection into a TreeSet:

Collection<String> sortedFrenchWords = new TreeSet<>(dictionary.values());
 

A more advanced use of a map is where the associated value can be a collection; that is, each key can be associated with any number of values. You declare such a map as follows:

Map<String, Collection<Integer>> lotterySyndicate = new HashMap<>();
 
  • Note the second formal type parameter is a Collection of Integer[1] objects. Take care to include both ending angle-brackets.

You use the normal put() method to place a key and value into the map, but need to create a collection capable of being the value associated with the key:

[1] Using the Integer wrapper class since primitives are not allowed in collections.
// John's lottery numbers
Collection<Integer> numbersForJohn = new TreeSet<>();
numbersForJohn.add(4);
numbersForJohn.add(16);
numbersForJohn.add(23);
numbersForJohn.add(29);
numbersForJohn.add(36);
numbersForJohn.add(42);
lotterySyndicate.put("John", numbersForJohn);
        
// Sue's lottery numbers
Collection<Integer> numbersForSue = new TreeSet<>();
numbersForSue.add(9);
numbersForSue.add(11);
numbersForSue.add(19);
numbersForSue.add(25);
numbersForSue.add(36);
numbersForSue.add(37);
lotterySyndicate.put("Sue", numbersForSue);

// Output the lottery numbers
System.out.println(lotterySyndicate);
 

In the next lesson we will define a map to store the zookeeper's responsibilities.

Next lesson: 11.4 Using Map for the zookeepers responsibilities


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image