Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. new HashMap<>() / map.put() / get() / getOrDefault()

new HashMap<>() / map.put() / get() / getOrDefault()

Methods for creating a map that manages key-value pairs, and for adding or retrieving elements. HashMap is well-suited for associative array–style usage because value lookups by key run in O(1) time.

Syntax

import java.util.HashMap;

// Creates an empty HashMap.
new HashMap<KeyType, ValueType>();

// Adds or updates a key-value pair.
map.put(K key, V value);

// Returns the value for the specified key.
map.get(Object key);

// Returns a default value if the key does not exist (Java 8+).
map.getOrDefault(Object key, V defaultValue);

// Adds the entry only if the key does not already exist (Java 8+).
map.putIfAbsent(K key, V value);

Method List

MethodDescription
new HashMap<>()Creates an empty HashMap. The default initial capacity is 16 and the load factor is 0.75.
put(K key, V value)Adds a key-value pair. If the key already exists, the value is overwritten and the previous value is returned.
get(Object key)Returns the value associated with the specified key. Returns null if the key does not exist.
getOrDefault(Object key, V defaultValue)Returns the value for the key if it exists, or defaultValue if it does not.
putIfAbsent(K key, V value)Adds the value only if the key does not exist (or its current value is null).

Sample Code

import java.util.HashMap;

// Create a HashMap and add entries.
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 92);
scores.put("Carol", 78);
System.out.println(scores); // Order is not guaranteed (HashMap does not preserve insertion order).

// Use get() to retrieve the value for a key.
System.out.println(scores.get("Alice")); // Prints "85".
System.out.println(scores.get("Dave"));  // Prints "null" because the key does not exist.

// Using put() on an existing key overwrites its value.
scores.put("Alice", 90); // Update Alice's score.
System.out.println(scores.get("Alice")); // Prints "90".

// Use getOrDefault() to specify a fallback value.
int score = scores.getOrDefault("Dave", 0);
System.out.println(score); // Prints "0" because the key does not exist.

// Use putIfAbsent() to add only when the key is absent.
scores.putIfAbsent("Bob", 100); // Bob already exists, so nothing is added.
scores.putIfAbsent("Dave", 70); // Dave does not exist, so the entry is added.
System.out.println(scores.get("Bob"));  // Prints "92" (unchanged).
System.out.println(scores.get("Dave")); // Prints "70".

// Example: counting word occurrences using a String key.
String sentence = "java is fun and java is easy";
HashMap<String, Integer> counter = new HashMap<>();
for (String word : sentence.split(" ")) {
    counter.put(word, counter.getOrDefault(word, 0) + 1);
}
System.out.println(counter); // Displays the occurrence count for each word.

Notes

HashMap stores data based on the hash value of each key, so adding, retrieving, and removing elements all run in O(1) time on average. However, HashMap does not guarantee element order. Use LinkedHashMap to preserve insertion order, or TreeMap to keep keys in ascending order at all times.

HashMap allows one null key and multiple null values. If you need thread-safe operations, use ConcurrentHashMap instead.

To remove entries or check for key existence, see remove() / containsKey(). To retrieve all keys or values, see keySet() / values() / entrySet().

If you find any errors or copyright issues, please .