This tutorial explains the usage of Maps and HashMap with Java.

1. Using maps

1.1. Map and HashMap

The Map interface defines an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The HashMap class is an efficient implementation of the Map interface.

1.2. Example program

To see the following code snippets in action, put them into this main method where put test code here is stated.

package com.vogella.java.collections.map;

import java.util.HashMap;
import java.util.Map;

public class MapTester {
    public static void main(String[] args) {
        // put test code here
    }
}

1.3. Initialize a HashMap in Java

The following code demonstrates how to initialize a HashMap in Java.

1.3.1. Initialize an empty map

In the following code an empty map with keys and objects of type Strings is initialized .

Map<String, String> map = Map.of();

1.3.2. Initialize a unmodifiable map with Map.of for small maps

In following example a map with several entries is initialized. This factory method supports a maximum of 10 key-value pairs and requires at least Java 9.

Map<String, String> map = Map.of("key1","value1", "key2", "value2");

1.3.3. Initialize an unmodifiable map via the Map.ofEntries();

Map<String, String> map = Map.ofEntries(
                    Map.entry("key1","value1"),
                    Map.entry("key2", "value2"),
                    // more
                    Map.entry("key100", "value100")
                );

1.3.4. Initialize a map via the new operator

The following creates a map via the new operator and add multiple entries to it via the put operator.

Map<String, String> map = new HashMap<>();
map.put("Android", "Mobile");
map.put("Eclipse IDE", "Java");
map.put("Eclipse RCP", "Java");
map.put("Git", "Version control system");

1.4. Remove an entry from a map

You can remove an entry from a map via the remove method.

Map<String, String> map = Map.of("Android","Mobile OS", "Flutter", "Development environment");
map.remove("Android");

1.5. Process the map

To process every element a map you can use the forEach method, which take a lambda as parameter.

map.forEach((k, v) -> System.out.printf("%s %s%n", k, v));

1.6. Convert keys in a Map to an array or a list

You can convert your keys or values to an array or list. The following code demonstrates that.

Map<String, String> map = new HashMap<>();
map.put("Android", "Mobile");
map.put("Eclipse IDE", "Java");
map.put("Eclipse RCP", "Java");
map.put("Git", "Version control system");

// convert keys to array
String[] keys = map.keySet().toArray(new String[map.keySet().size()])

for (String string : keys) {
    System.out.println(string);
}
// convert keys to list
List<String> list = new ArrayList<String>(map.keySet());
for (String string : list) {
    System.out.println(string);
}

1.7. Getting the current value or a default for a map

You can use the getOrDefault() method to return the value for a key or a default value if the key is not present in the map.

Map<String,Integer> map = new HashMap<>();
map.put("Android", 1 + map.getOrDefault("Android", 0));

// write to command line
map.forEach((k, v) -> System.out.printf("%s %s%n", k, v));

1.8. Compute if absent

The computeIfAbsent calculates and adds an entry to the map if it is not present in the map.

Map<String,Integer> map = Map.of();

Integer calculatedVaue = map.computeIfAbsent("Java", it -> 0);
System.out.println(calculatedVaue);

map.keySet().forEach(key -> System.out.println(key + " " + map.get(key)));

2. vogella training and consulting support

Copyright © 2012-2019 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.