Sobes.tech
Junior — Middle

Can you explain what the Map interface in Java is and how it is used?

sobes.tech AI

Answer from AI

The Map interface in Java represents a collection that stores key-value pairs. Each key is unique, and it can be used to quickly retrieve the corresponding value.

Main features of Map:

  • Keys are unique, values can be duplicated.
  • Allows fast search, addition, and removal of elements by key.
  • It is not part of the Collection interface but a separate interface.

Example of using Map:

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

Map<String, Integer> ages = new HashMap<>();
ages.put("Ivan", 25);
ages.put("Maria", 30);

int age = ages.get("Ivan"); // Gets 25

if (ages.containsKey("Maria")) {
    System.out.println("Maria's age: " + ages.get("Maria"));
}

Thus, Map is used for storing and quickly accessing data by a unique key.

Can you explain what the Map interface in Java is and… - sobes.tech