Java : HashMap with Examples

HashMap (Java SE 18 & JDK 18) API Examples.
You will find code examples on most HashMap methods.


Summary

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key.

Class diagram

final var map = new HashMap<String, Integer>();
System.out.println(map); // {}

map.put("a", 10);
map.put("b", 20);
map.put("c", 30);
System.out.println(map); // {a=10, b=20, c=30}

System.out.println(map.get("a")); // 10
System.out.println(map.get("b")); // 20
System.out.println(map.get("X")); // null

map.remove("b");
System.out.println(map); // {a=10, c=30}

Constructors

HashMap ()

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).

final var map = new HashMap<String, Integer>();
System.out.println(map); // {}
System.out.println(map.isEmpty()); // true

map.put("a", 10);
map.put("b", 20);
map.put("c", 30);

System.out.println(map); // {a=10, b=20, c=30}
System.out.println(map.size()); // 3

HashMap (int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

final var map = new HashMap<String, Integer>(10000000);
System.out.println(map); // {}

final var startTime = System.nanoTime();

for (int i = 0; i < 1000000; i++) {
    map.put(String.valueOf(i), i);
}

final var endTime = System.nanoTime();

// 0.143976 sec.
System.out.printf("%f sec.%n", (endTime - startTime) / 1000000000.0);
final var map = new HashMap<String, Integer>(1);
System.out.println(map); // {}

final var startTime = System.nanoTime();

for (int i = 0; i < 1000000; i++) {
    map.put(String.valueOf(i), i);
}

final var endTime = System.nanoTime();

// 0.197840 sec.
System.out.printf("%f sec.%n", (endTime - startTime) / 1000000000.0);

HashMap (int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

final var map = new HashMap<String, Integer>(16, 0.05f);
System.out.println(map); // {}

final var startTime = System.nanoTime();

for (int i = 0; i < 1000000; i++) {
    map.put(String.valueOf(i), i);
}

final var endTime = System.nanoTime();

// 0.256490 sec.
System.out.printf("%f sec.%n", (endTime - startTime) / 1000000000.0);
final var map = new HashMap<String, Integer>(16, 0.75f);
System.out.println(map); // {}

final var startTime = System.nanoTime();

for (int i = 0; i < 1000000; i++) {
    map.put(String.valueOf(i), i);
}

final var endTime = System.nanoTime();

// 0.188262 sec.
System.out.printf("%f sec.%n", (endTime - startTime) / 1000000000.0);

HashMap (Map<? extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map.

final var m = Map.of("a", 10, "b", 20, "c", 30);

final var map = new HashMap<>(m);
System.out.println(map); // {a=10, b=20, c=30}
System.out.println(map.size()); // 3

Methods

void clear ()

Removes all of the mappings from this map.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

System.out.println(map); // {a=1, b=2, c=3}
System.out.println(map.size()); // 3

map.clear();
System.out.println(map); // {}
System.out.println(map.size()); // 0

Object clone ()

Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

System.out.println(map); // {a=1, b=2, c=3}

final var cloned = map.clone();
System.out.println(cloned); // {a=1, b=2, c=3}
System.out.println(cloned.getClass()); // class java.util.HashMap

V compute (K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var func = new BiFunction<String, Integer, Integer>() {
    @Override
    public Integer apply(String key, Integer value) {
        if (value == null) {
            return -100;
        } else {
            return value * 10;
        }
    }
};

final var ret1 = map.compute("a", func);
System.out.println(ret1); // 10
System.out.println(map); // {a=10, b=2, c=3}

final var ret2 = map.compute("b", func);
System.out.println(ret2); // 20
System.out.println(map); // {a=10, b=20, c=3}

final var ret3 = map.compute("c", func);
System.out.println(ret3); // 30
System.out.println(map); // {a=10, b=20, c=30}

final var ret4 = map.compute("X", func);
System.out.println(ret4); // -100
System.out.println(map); // {a=10, b=20, c=30, X=-100}
final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var ret = map.compute("b", (key, value) -> null);
System.out.println(ret); // null
System.out.println(map); // {a=1, c=3}

V computeIfAbsent (K key, Function<? super K,? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

final var map = new HashMap<String, String>();
map.put("a", "aaa");
map.put("b", "bbb");
System.out.println(map); // {a=aaa, b=bbb}

final var func = new Function<String, String>() {
    @Override
    public String apply(String key) {
        if ("c".equals(key)) {
            return "ccc";
        } else {
            return null;
        }
    }
};

final var ret1 = map.computeIfAbsent("a", func);
System.out.println(ret1); // aaa
System.out.println(map); // {a=aaa, b=bbb}

final var ret2 = map.computeIfAbsent("b", func);
System.out.println(ret2); // bbb
System.out.println(map); // {a=aaa, b=bbb}

final var ret3 = map.computeIfAbsent("c", func);
System.out.println(ret3); // ccc
System.out.println(map); // {a=aaa, b=bbb, c=ccc}

final var ret4 = map.computeIfAbsent("d", func);
System.out.println(ret4); // null
System.out.println(map); // {a=aaa, b=bbb, c=ccc}
final var map = new HashMap<String, List<String>>();
System.out.println(map); // {}

map.computeIfAbsent("a", (key) -> new ArrayList<>()).add("a-1");
System.out.println(map); // {a=[a-1]}

map.computeIfAbsent("a", (key) -> new ArrayList<>()).add("a-2");
System.out.println(map); // {a=[a-1, a-2]}

map.computeIfAbsent("b", (key) -> new ArrayList<>()).add("b-1");
System.out.println(map); // {a=[a-1, a-2], b=[b-1]}

V computeIfPresent (K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var func = new BiFunction<String, Integer, Integer>() {
    @Override
    public Integer apply(String key, Integer value) {
        return value * 10;
    }
};

final var ret1 = map.computeIfPresent("a", func);
System.out.println(ret1); // 10
System.out.println(map); // {a=10, b=2, c=3}

final var ret2 = map.computeIfPresent("b", func);
System.out.println(ret2); // 20
System.out.println(map); // {a=10, b=20, c=3}

final var ret3 = map.computeIfPresent("c", func);
System.out.println(ret3); // 30
System.out.println(map); // {a=10, b=20, c=30}

final var ret4 = map.computeIfPresent("X", func);
System.out.println(ret4); // null
System.out.println(map); // {a=10, b=20, c=30}
final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var ret = map.computeIfPresent("b", (k, v) -> null);
System.out.println(ret); // null
System.out.println(map); // {a=1, c=3}

boolean containsKey (Object key)

Returns true if this map contains a mapping for the specified key.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

System.out.println(map); // {a=1, b=2, c=3}

System.out.println(map.containsKey("a")); // true
System.out.println(map.containsKey("b")); // true
System.out.println(map.containsKey("c")); // true
System.out.println(map.containsKey("X")); // false
System.out.println(map.containsKey("")); // false

boolean containsValue (Object value)

Returns true if this map maps one or more keys to the specified value.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.put("X", 3);

System.out.println(map); // {a=1, b=2, c=3, X=3}

System.out.println(map.containsValue(0)); // false
System.out.println(map.containsValue(1)); // true
System.out.println(map.containsValue(2)); // true
System.out.println(map.containsValue(3)); // true
System.out.println(map.containsValue(4)); // false

Set<Map.Entry<K,V>> entrySet ()

Returns a Set view of the mappings contained in this map.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var entries = map.entrySet();
System.out.println(entries); // [a=1, b=2, c=3]

map.replace("b", 20);
System.out.println(map); // {a=1, b=20, c=3}
System.out.println(entries); // [a=1, b=20, c=3]

entries.remove(Map.entry("a", 1));
System.out.println(map); // {b=20, c=3}
System.out.println(entries); // [b=20, c=3]

for (final var entry : entries) {
    entry.setValue(entry.getValue() * 10);
}

System.out.println(map); // {b=200, c=30}
System.out.println(entries); // [b=200, c=30]

V get (Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

System.out.println(map); // {a=1, b=2, c=3}

System.out.println(map.get("a")); // 1
System.out.println(map.get("b")); // 2
System.out.println(map.get("c")); // 3
System.out.println(map.get("X")); // null
System.out.println(map.get("")); // null

boolean isEmpty ()

Returns true if this map contains no key-value mappings.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);

System.out.println(map); // {a=1, b=2, c=3}
System.out.println(map.size()); // 3
System.out.println(map.isEmpty()); // false

map.clear();

System.out.println(map); // {}
System.out.println(map.size()); // 0
System.out.println(map.isEmpty()); // true

Set<K> keySet ()

Returns a Set view of the keys contained in this map.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var keys = map.keySet();
System.out.println(keys); // [a, b, c]

map.put("d", 4);
System.out.println(map); // {a=1, b=2, c=3, d=4}
System.out.println(keys); // [a, b, c, d]

keys.remove("a");
System.out.println(map); // {b=2, c=3, d=4}
System.out.println(keys); // [b, c, d]

V merge (K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var func = new BiFunction<Integer, Integer, Integer>() {
    @Override
    public Integer apply(Integer oldValue, Integer newValue) {
        return oldValue + newValue;
    }
};

final var ret1 = map.merge("a", 1000, func);
System.out.println(ret1); // 1001
System.out.println(map); // {a=1001, b=2, c=3}

final var ret2 = map.merge("b", 1000, func);
System.out.println(ret2); // 1002
System.out.println(map); // {a=1001, b=1002, c=3}

final var ret3 = map.merge("c", 1000, func);
System.out.println(ret3); // 1003
System.out.println(map); // {a=1001, b=1002, c=1003}

final var ret4 = map.merge("d", 1000, func);
System.out.println(ret4); // 1000
System.out.println(map); // {a=1001, b=1002, c=1003, d=1000}

final var ret5 = map.merge("b", 1000, (k, v) -> null);
System.out.println(ret5); // null
System.out.println(map); // {a=1001, c=1003, d=1000}

V put (K key, V value)

Associates the specified value with the specified key in this map.

final var map = new HashMap<String, Integer>();
System.out.println(map); // {}

System.out.println(map.put("a", 1)); // null
System.out.println(map); // {a=1}

System.out.println(map.put("b", 2)); // null
System.out.println(map); // {a=1, b=2}

System.out.println(map.put("c", 3)); // null
System.out.println(map); // {a=1, b=2, c=3}

System.out.println(map.put("a", 999)); // 1
System.out.println(map); // {a=999, b=2, c=3}

void putAll (Map<? extends K,? extends V> m)

Copies all of the mappings from the specified map to this map.

final var map = new HashMap<String, Integer>();
System.out.println(map); // {}

map.putAll(Map.of());
System.out.println(map); // {}

map.putAll(Map.of("a", 1, "b", 2));
System.out.println(map); // {a=1, b=2}

map.putAll(Map.of("c", 3, "d", 4, "e", 5));
System.out.println(map); // {a=1, b=2, c=3, d=4, e=5}

map.putAll(Map.of("a", 901, "b", 902, "z", 100));
System.out.println(map);  // {a=901, b=902, z=100, c=3, d=4, e=5}

V remove (Object key)

Removes the mapping for the specified key from this map if present.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

System.out.println(map.remove("b")); // 2
System.out.println(map); // {a=1, c=3}

System.out.println(map.remove("z")); // null
System.out.println(map); // {a=1, c=3}

int size ()

Returns the number of key-value mappings in this map.

final var map = new HashMap<String, Integer>();

System.out.println(map); // {}
System.out.println(map.size()); // 0

map.put("a", 1);
System.out.println(map); // {a=1}
System.out.println(map.size()); // 1

map.put("b", 2);
System.out.println(map); // {a=1, b=2}
System.out.println(map.size()); // 2

map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}
System.out.println(map.size()); // 3

Collection<V> values ()

Returns a Collection view of the values contained in this map.

final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
System.out.println(map); // {a=1, b=2, c=3}

final var values = map.values();
System.out.println(values); // [1, 2, 3]

map.replace("b", 20);
System.out.println(map); // {a=1, b=20, c=3}
System.out.println(values); // [1, 20, 3]

values.remove(1);
System.out.println(map); // {b=20, c=3}
System.out.println(values); // [20, 3]

//values.add(4); // UnsupportedOperationException

Methods declared in AbstractMap

equals, hashCode, toString

Please see the link below.

Methods declared in Map

equals, forEach, getOrDefault, hashCode, putIfAbsent, remove, replace, replace, replaceAll

Please see the link below.


Related posts

To top of page