
Initializing and Using Maps, HashMaps and SortedMaps in Java
The abstract Map class in Java is a very useful utility especially in cases where there is a need to store object pairs in a generic collection, if you’d rather not create your own container objects for such a coupling. HashMap is one of the most commonly used implementations of Java maps and Java 9 offers an even cooler method for its initialization.
I want to start with a quick refresher for those who had previously little exposure to Java maps (or have had no exposure at all) by demonstrating at first, the old school way of instantiating a Map as HashMap and initializing it with some pre-existing values. Map collections can accommodate Java objects in comma-separated pairs which could be as simple as two Integers or Strings or each of both, and can be as complicated as holding couplings of other objects collections – even nested ones. An extreme example can be like the following:
Map<Map<K,V>,Map<K,V>> nestedMap;
A relatively simpler example use-case I will demonstrate is storing a grouping of different editions of a book with corresponding unit prices. In this case, the unit price is stored as a Double object coupled with the book edition which is denoted by a code stored as String, and here I will demonstrate with example code in the following sections:
How to create and initialize a Java Map?
Table of Contents
Defining a Map and Instantiating with a HashMap
import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // in Java 6 and earlier Map<Double, String> bookEditionPriceMap = new HashMap<String, BigDecimal>(); // in Java 7 or later type arguments for the instantiated class are considered redundant when they are already defined in the class of the variable. Map<Double, String> bookEditionPriceMap = new HashMap<>(); // instantiating just as HashMap<>() is referred to as type inference with diamond operator // Initializing the HashMap (pre-Java 9) bookEditionPriceMap.put(39.95, "bookpaperback"); bookEditionPriceMap.put(49.95, "bookhardcover"); bookEditionPriceMap.put(19.95, "ebookepub"); bookEditionPriceMap.put(29.95, "ebookpdf"); bookEditionPriceMap.put(24.95, "ebookazw");
In the example above, we first create a map, and then put entries to it. Using these methods, we end up with a dynamic Map which can be dynamically edited, by creating new entries or removing items from it.
Java 9 brings a built-in method to the Map class called “of( … )” allowing us to initialize the map directly in just one line:
// Java 9 and later - inline initialization on a single line Map<Double,String> map = Map.of(new Double(19.95),"ebookepub", new BigDecimal(29.95),"ebookpdf", new BigDecimal(24.95), "ebookazw");
How to sort a Java Map?
Sorting a Java Map the Easy Way
What if we want the elements of the Map automatically sorted and quickly locate the products with the highest and the lowest price respectively? Enter SortedMap implemented with a TreeMap.
Here’s the example adapted:
// Convert our existing bookEditionPriceMap to a (sorted) TreeMap SortedMap<Double, String> bookEditionSortedPriceMap = new TreeMap<>(bookEditionPriceMap); // Getting the cheapest product without iterating over the map System.out.println("Our cheapest edition of the book costs "+bookEditionSortedPriceMap.firstKey()); System.out.println("Our most expensive edition of the book costs "+bookEditionSortedPriceMap.lastKey() );
So which part of the code is doing the sorting? Well, none. The point of using a Sorted Map is it sorts its items automatically when they are added to the collection. What’s more is that it is already included in the standard SDK – no need to import a 3rd party library. To see the list of all items sorted in ascending order, see the next section.
How to Iterate through the Map, HashMap, SortedMap or the TreeMap?
Since they all are based on the generic Map class, iterating can be done in the same way for all of them using a for loop which has the least verbosity:
// Iterating over the map System.out.println("We have the following book editions with typical prices of:"); for (Map.Entry<Double, String> entry : bookEditionSortedPriceMap.entrySet()) { System.out.println(entry.getValue() + " : " + entry.getKey()); }