Sobes.tech
Junior

What is the Map interface in Java?

sobes.tech AI

Answer from AI

Map is an interface in Java representing a collection of key-value pairs. Each key is unique and corresponds to a single value. Unlike other collections like List or Set, Map does not inherit from the Collection interface.

Main operations:

  • put(K key, V value): adds a key-value pair or updates the value for an existing key.
  • get(Object key): returns the value associated with the specified key, or null if the key is not found.
  • remove(Object key): removes the pair by key.
  • containsKey(Object key): checks for the presence of a key.
  • containsValue(Object value): checks for the presence of a value.
  • size(): returns the number of pairs.
  • isEmpty(): checks if the Map is empty.
  • clear(): removes all pairs.
  • keySet(): returns a Set of keys.
  • values(): returns a Collection of values.
  • entrySet(): returns a Set of Map.Entry<K, V> pairs.

Examples of implementations:

  • HashMap: does not guarantee element order, fast for basic operations.
  • LinkedHashMap: maintains insertion order or access order.
  • TreeMap: stores elements in sorted order by key. The order is determined by the natural ordering of keys or a comparator.
  • ConcurrentHashMap: thread-safe implementation for multi-threaded environments.

Usage example:

// Creating a HashMap
Map<String, Integer> scores = new HashMap<>();

// Adding elements
scores.put("Alice", 95);
scores.put("Bob", 88);
scores.put("Charlie", 92);

// Getting value by key
int aliceScore = scores.get("Alice"); // 95

// Checking for key presence
boolean containsBob = scores.containsKey("Bob"); // true

// Iterating over EntrySet
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
What is the Map interface in Java? — Java - sobes.tech