Sobes.tech
Junior — Middle

What are the main methods and operations that can be performed on Map data structures?

sobes.tech AI

Answer from AI

In Android (and Java in general), the Map data structure represents a collection of key-value pairs. The main methods and operations on Map include:

  • put(K key, V value) — adds or updates a key-value pair.
  • get(Object key) — returns the value for the key or null if the key is absent.
  • 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.
  • keySet() — returns a set of all keys.
  • values() — returns a collection of all values.
  • entrySet() — returns a set of all key-value pairs.
  • size() — the number of elements in the Map.
  • clear() — clears the Map.

Example usage:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);

int count = map.get("apple"); // 3

if (map.containsKey("banana")) {
    map.remove("banana");
}

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}
What are the main methods and operations that can be… - sobes.tech