Java HashMap: 5 Questions and Answers You Should Know Of

1. What is Java HashMap?

Java HashMap is a collection that implements from the Map interface. It has been around since JDK 1.2. HashMap is implemented on top of HashTable and therefore they both have a lot of similarities. HashMap in Java stores key-value pairs and provides several methods to retrieve and manipulate them. You can check the full list in its’ documentation.

Fun fact: Even though HashMap is a collection it doesn’t implement the Collection interface like Set and List do.

This is how ArrayList inherits for example:

arraylist inheritance

And this is the same info about HashMap:

hashmap inheritance

2. Is Java HashMap ordered / sorted?

Java HashMap does not keep the order of inserted objects. This means that when you iterate over a map the objects are in a random order. But you can access values in a map by the keys. We’ll take a look at this a bit later under examples.

3. What is HashMap initial capacity and load factor?

Java HashMap has an initial capacity of 16 and a load factor of 0.75. What does it all mean? This means that when you first create a HashMap then it has 16 buckets in the hash table. Simply put, it has space for 16 key-value pairs.

java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity

Load factor shows how full a map can get before it will be resized. It is as simple as that. When map is resized then it will double its’ size. In other words, it will have twice the number of buckets. For example if the initial capacity is 16 then the new capacity will be 2 x 16 = 32.

java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity java hashmap capacity

Capacity and load factor both affect HashMaps’ performance. Higher values increases the lookup cost of elements but decrease the space overhead. This affects most of the operations HashMap offers (for example get() and put()). It is said that the default load factor of 0.75 is usually a well balanced choice. With this in mind, in case you know for sure there’s going to be a huge numbers of entries in a map, you should consider setting a higher initial capacity for your map during its’ creation. So that the map doesn’t have to automatically resize itself many times to grow the table.

This is how you can set initial capacity and load factor:

Map<Character, String> withCapacity = new HashMap<>(50);
Map<Character, String> withCapacityAndLoadFactor = new HashMap<>(50, 0.6f);

4. Is Java HashMap Thread Safe / Synchronized?

HashMap in Java is not synchronized. In case there are multiple threads reading from/writing to a HashMap, you might get some unexpected results. If this is the case then you can wrap it using the Collections.synchronizedMap method.

Map<Character, String> synchronizedMap = 
        Collections.synchronizedMap(new HashMap<>());

5. How To Use Java HashMap?

Java HashMap is simple to use. Lets take a look at some examples of it.

To begin with, let’s create a HashMap that stores letters as keys and words as values. We can call it wordsByLetters. In this map for each letter corresponds a word starting with the letter.

// Let's create a map. Its' key is a letter and
// value is a word corresponding to this letter
Map<Character, String> wordsByLetters = new HashMap<>();
wordsByLetters.put('P', "Pineapple");
wordsByLetters.put('S', "Strawberry");

Now, we can try to find a word under letter S:

// Find word under letter S
String wordByLetterS = wordsByLetters.get('S');
System.out.println("Word under letter S: " + wordByLetterS);

Output:

Word under letter S: Strawberry

Another option is to set HashMap to return a default value when it can’t find a word under a specified letter:

// When word in a map doesn't exist by letter B 
// then it returns default value 'Banana'
System.out.println(
        "Word returned: " + wordsByLetters.getOrDefault('B', "Banana")
);

Output:

Word returned: Banana

We can also add another maps’ entries into our existing wordsByLetters map:

// Create a map and populate it. 
Map<Character, String> otherWordsByLetters = 
        new HashMap<Character, String>() {{
            put('T', "Tiger");
            put('W', "Winter");
        }};

// Add entries of otherWordsByLetters into wordsByLetters map
wordsByLetters.putAll(otherWordsByLetters);

Let’s see what we have in the map:

// Let's display all the letters and corresponding words
for (Entry<Character, String> letterWordPair : wordsByLetters.entrySet()) {
    System.out.println(
            "Letter: " + letterWordPair.getKey() + ", " +
            "Word: " + letterWordPair.getValue());
}

Output:

Letter: P, Word: Pineapple
Letter: S, Word: Strawberry
Letter: T, Word: Tiger
Letter: W, Word: Winter

In addition, there are values and keySet methods to fetch all the values or all the keys in a map.

// Iterate over keys (letters) and display them. 
wordsByLetters.keySet().forEach(letter -> System.out.println(letter));

// Iterate over values (words) and display them
wordsByLetters.values().forEach(word -> System.out.println(word));

As a final example let’s remove a key-value (letter-word) pair from the map:

// Check if letter W is in the map.
System.out.println("Contains key: " + wordsByLetters.containsKey('W'));

// Remove letter W from the map
wordsByLetters.remove('W');

// Check if letter W is in the map
System.out.println("Contains key: " + wordsByLetters.containsKey('W'));

Output:

Contains key: true
Contains key: false

Conclusion

HashMap in Java is a collection that implements from the Map interface. It is implemented on top of HashTable. HashMap stores key-value pairs and doesn’t guarantee the order of the elements. It is also not synchronized. When you create a HashMap in Java then its’ initial capacity is 16 and its’ load factor is 0.75. When the map resizes, its’ capacity doubles.

I hope you have found it useful to read. Feel free to leave comments or feedback!

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *