Java- Hashmap Functionality
Syntax
Map<Key-Type,Value-Tpe> mapReference=new HashMap<>();
| Return type | Method | Usage | Description |
|---|---|---|---|
V | get(Object key) | mapReference.get(key); | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
default V | getOrDefault(Object key, V defaultValue) | mapReference.getOrDefault(key,0); | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
V | put(K key, V value) | mapReference.put(key,value); | Associates the specified value with the specified key in this map (optional operation). |
V | remove(Object key) | mapReference.remove(key); | Removes the mapping for a key from this map if it is present (optional operation). |
Collection<V> | values() | mapReference.values(); | Returns a Collection view of the values contained in this map. |
boolean | containsKey(Object key) | mapReference.containsKey(key); | Returns true if this map contains a mapping for the specified key. |
boolean | containsValue(Object value) | mapReference.containsValue(value); | Returns true if this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> | entrySet() | mapReference.entrySet(); | Returns a Set view of the mappings contained in this map. |
Set<K> | keySet() | mapReference.keySet(); | Returns a Set view of the keys contained in this map. |
Iterating over entrySet
// Java program to demonstrate iteration over
// Map.entrySet() entries using for-each loop
import java.util.Map;
import java.util.HashMap;
class IterationDemo
{
public static void main(String[] arg)
{
Map<String,String> map = new HashMap<String,String>();
// enter name/url pair
map.put("GFG", "geeksforgeeks.org");
map.put("Practice", "practice.geeksforgeeks.org");
map.put("Code", "code.geeksforgeeks.org");
map.put("Quiz", "quiz.geeksforgeeks.org");
// using for-each loop for iteration over Map.entrySet()
for (Map.Entry<String,String> entry : map.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
}
FAilfast/FAilSAfe
https://www.javatpoint.com/fail-fast-and-fail-safe-iterator-in-java