Sobes.tech
Junior — Middle

What is the main task of the Map data structure and what is its advantage?

sobes.tech AI

Answer from AI

The main task of the Map data structure is to store "key-value" pairs with the ability to quickly access a value by its key. The advantage of Map is that it provides efficient search, insertion, and deletion of elements, usually in near-constant time (O(1)), which is significantly faster than list traversal.

Example of using Map in Java:

import java.util.HashMap;

public class Example {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 5);

        int count = map.get("apple"); // Get the value by the key "apple"
        System.out.println("Number of apples: " + count);
    }
}