java
CopyEdit
add(E e); // Adds element to the set
remove(Object o); // Removes the specified element
contains(Object o); // Checks if the set contains the specified element
size(); // Returns the number of elements in the set
isEmpty(); // Checks if the set is empty
iterator(); // Returns an iterator for the set
clear(); // Removes all elements from the set
toArray(); // Converts the set to an array
java
CopyEdit
put(K key, V value); // Inserts OR UPDATE a key-value pair
putIfAbsent(K key, V value); // Inserts a key-value pair only if the key is not already mapped
get(Object key); // Returns the value associated with the key
getOrDefault(Object key, V defaultValue); // Returns the value or a default value if the key is not found
containsKey(Object key); // Checks if the map contains the specified key
containsValue(Object value); // Checks if the map contains the specified value
remove(Object key); // Removes the mapping for the specified key
replace(K key, V value); // Replaces the value for a key if it exists
keySet(); // Returns a set of all keys
values(); // Returns a collection of all values
entrySet(); // Returns a set of key-value pairs
size(); // Returns the number of key-value mappings
isEmpty(); // Checks if the map is empty
***Find Key By Value***
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
if (entry.getValue().equals(2)) {
System.out.println(entry.getKey());
break;
}
}
getKey()| Expression | Used On | Returns | Example Use |
|---|---|---|---|
map.get(key) |
Map<K, V> |
Value (V) |
map.get("apple") returns 10 |
entry.getValue() |
Map.Entry<K,V> |
Value (V) |
Inside loop: entry.getValue() |
Similarly, entry.getKey() gets the key of that entry.
java
CopyEdit
Map.Entry<String, Integer> entry = Map.entry("banana", 7);
System.out.println(entry.getKey()); // banana
System.out.println(entry.getValue()); // 7