<aside> π‘ Key-value structures comes under the Map Interface.
</aside>
K
is the type for keys.V
is the type for values.get(k)
β Fetches the value for the key k
.put(k,v)
β Updates the value for key k
.public interface Map<K,V>{
V get(Object key);
V put(K key, V value);
boolean containsKey(Object key);
boolean containsValue(Object value);
...
}
put(k,v)
returns the previous value associated with k
or null
.Map
has the following default method β V getDefault(Object key,V defaultValue);
Example:
Map<String,Integer> scores = ....;
int score = scores.getDefault(bat,0);
//sets score to 0 if key bat is not present
Now we can update the entry for key bat
as follows:
scores.put(bat, scores.getDefault(bat,0)+newscore); //Updates score of batsman with previus score + newscore
Can Use putIfAbsent()
to initialize a missing key.
scores.putIfAbsent(bat,0); //Sets the value of key bat to 0 if the key does not exist, else do nothing.
scores.put(bat, scores.get(bat)+newscore);
// now update value with newscore because the key bat is guaranteed to have a value(either 0 or
// the previously stored value)
Or use merge()
score.merge(bat,newscore, Integer::sum);
newscore
if key bat does not exist.Integer::sum
Methods to extract keys and values:
Set<K> keySet();
βIs a Set because keys should not have duplicates.Collection<V> values();
Set<Map.Entry<K,V>> entrySet()
β A set of Key value mappings. The type returned is a special Set
of type Map.Entry
(Set of Map.Entry).Now use the above to iterate through a Map
Set<String> keys = strmap.keySet();
for(String key : keys){
// do something with key....
}
get()
function for the corresponding key.So use entrySet()
to operate on key and associated value without looking up the map again:
for(Map.Entry<String,Employee> entry : staff.entrySet()){
String k = entry.getKey();
Employee v = entry.getValue();
// now do something with k and v
}
We looked at the interface Map
. Moving forward, we now look at the concrete implementations of Map