Here is all about Map of Java
sequenceDiagram
java.lang.Object->>java.util.AbstractMap:
Interface | Hash Table | Resizable Array | Balanced Tree | Linked List |
---|---|---|---|---|
Map | HashMap | TreeMap | ||
SortedMap | TreeMap | |||
NavigableMap | TreeMap | |||
Map.Entry(Inner Class of Map) |
Methods of Abstract Map(Abstract Class) | Does This |
---|---|
1. clear() | Removes all of the mappings from this map . |
2.clone() | Returns a shallow copy of this map. |
3. containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
4. containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
5.entrySet() | Returns a Set view of the mappings contained in this map. |
6. equals(Object o) | Compares the specified object with this map for equality. |
7. get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
8. hashCode() | Returns the hash code value for this map. |
9. isEmpty() | Returns true if this map contains no key-value mappings. |
10. keySet() | Returns a Set view of the keys contained in this map. |
11. put(K key, V value) | Associates the specified value with the specified key in this map . |
12. putAll(Map m) | Copies all of the mappings from the specified map to this map . |
13. remove(Object key) | Removes the mapping for a key from this map if it is present. |
14.size() | Returns the number of key-value mappings in this map. |
15.toString() | Returns a string representation of this map. |
16.values() | Returns a Collection view of the values contained in this map. |
That is :
import java.util.Iterator;
import java.lang.Iterable;
Iterable<Map<Key, Value>> itr = map; → Cannot be Obtained
Or
Iterator<Map<Key, Value>> iterator = map.iterator(); → Cannot be Obtained
Interface | Description |
---|---|
Map | Maps unique keys to values. |
Map.Entry | Describes an element (a key/value) in a map. This is an inner class of Map. |
NavigableMap | It extends SortedMap to handle the retrieval of entries based on closest-match searches. |
SortedMap | It extends Map to keep the keys in ascending order. |
Methods of Map Interface | Does This |
---|---|
1. clear() | Removes all of the mappings from this map |
2. compute(K key, BiFunction remappingFunction) | Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
3. computeIfAbsent(K key, Function mappingFunction) | If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null. |
4. computeIfPresent(K key, BiFunction remappingFunction) | If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value. |
5. containsKey(Object key) | Returns true if this map contains a mapping for the specified key. |
6. containsValue(Object value) | Returns true if this map maps one or more keys to the specified value. |
7. entrySet() | Returns a Set view of the mappings(All Entries) contained in this map. |
8. equals(Object o) | Compares the specified object with this map for equality. |
9. forEach(BiConsumer action) | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
10. get(Object key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
11. getOrDefault(Object key, V defaultValue) | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
12. hashCode() | Returns the hash code value for this map. |
13. isEmpty() | Returns true if this map contains no key-value mappings. |
14.keySet() | Returns a Set view of the keys contained in this map. |
15.merge(K key, V value, BiFunction remappingFunction) | If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. |
16.put(K key, V value) | Associates the specified value with the specified key in this map. |
17.putAll(Map m) | Copies all of the mappings from the specified map to this map. |
18.putIfAbsent(K key, V value) | If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value. |
19.remove(Object key) | Removes the mapping for a key from this map if it is present. |
20.remove(Object key, Object value) | Removes the entry for the specified key only if it is currently mapped to the specified value. |
21.replace(K key, V value) | Replaces the entry for the specified key only if it is currently mapped to some value. |
22.replace(K key, V oldValue, V newValue) | Replaces the entry for the specified key only if currently mapped to the specified value. |
23.replaceAll(BiFunction function) | Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. |
24.size() | Returns the number of key-value mappings in this map. |
25.values() | Returns a Collection view of the values contained in this map. |
2. As Abstract Map implements Map interface and extends java.lang.Object class , HashMap inherits all of their functions.
graph TD;
Object-->|extends| AbstractMap;
Map-->|implements| AbstractMap;
AbstractMap-->|extends| HashMap;
Constructor | Does This |
---|---|
HashMap() | It constructs a new empty map. |
HashMap(int initialCapacity) | It constructs a new empty map, with the given initial capacity. |
HashMap(int initialCapacity, float loadFactor) | It constructs a new empty map, with the given initial capacity and the given load factor. |
HashMap(Map m) | It constructs a new map, with the same mappings as the given map. |
:ThresHold of HashMap, Capacity and LoadFactor:
--------------------------------------------------
ThresHold of HashMap :
The threshold of a HashMap is approximately the product of current capacity and load factor
LoadFactor :
The load factor is the measure that decides when to increase the capacity of the Map.
Capacity of HashMap:
Capacity is the number of buckets in the HashMap.
Default Capacity of HashMap: 16
That is empty HashMap created with capacity 16.
Default LoadFactor of HashMap: 0.75
That is empty HashMap created with Load Factor 0.75.
Default Threshold of HashMap: is 16 * 0.75 = 12.
That is empty HashMap created with threshold 12.
Index:
It is the integer value .
It is obtained after performing →
Bitwise AND operation on the Value of Hash of the Key and Array Size Minus One.
i.e., :| Index = hashcode(key) & (ArraySize – 1) |:
Bucket: It is a LinkedList structure of nodes.
Node: It is the elementary unit of a HashMap.
It contains the key-value pair and a link to the next node.
Next: Link to the next node.
It is represented as: Node<K,V> next.
Where K represents Key and V represents Value.
Rehashing: It is the process of doubling the capacity of the HashMap ,
after it reaches its Threshold. In java, HashMap continues to
rehash(by default) in the following sequence – 2^4, 2^5, 2^6, 2^7, …. so on.
It removes all the mappings of this map.
The map will be empty after this call returns.
Returns a shallow copy of the HashMap instance provided for cloning
but the keys and values themselves are not cloned.
Returns true if this map contains a mapping for the specified key.
Returns true if this map maps one or more keys to the specified value.
Performs the given action for each entry in this map
until all entries have been processed or the action throws an exception.
Syntax: get(key: Key)
Returns the value to which the specified key is mapped,
or null if this map contains no mapping for the key.
Syntax: getOrDefault(key: Key , defaultValue:Value)
Returns the value to which the specified key is mapped,
or defaultValue if this map contains no mapping for the key.
i.e.,getOrDefault(key:"One" , defaultValue:1)
then it will return the value for the key : "One"
Or, it will return the value for the value : 1
Most priority given or first search is Key for Value .
If not found , then it searches for defaultValue for value.
That is if "One" is not found then it searches for 1.
Returns true if this map contains no key-value mappings.
Returns a Set view of the keys contained in this map.
The set is backed by the map,
so changes to the map are reflected in the set, and vice-versa.
Note:
As Set<K> keySet()→ Is a Function that returns Set,
Hence, it call all those functions that Set contains,
Such as:
→forEach
→toArray()
→remove()
→removeIf()
→retainAll()
→removeAll()
→Stream()
→ParallelStream()
→spliterator()
→iterator()
→contains()
→containsAll()
...etc.
It does not support the add or addAll operations.
Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key,
the old value is replaced.
Copies all of the mappings from the specified map to this map.
These mappings will replace any mappings that this map had ,
for any of the keys currently in the specified map.
Removes the mapping for the specified key from this map if present.
Removes the entry for the specified key only if it is currently mapped to the specified value.
Replaces the entry for the specified key only if currently mapped to the specified value.
It replaces old value with new value.
Replaces each entry's value with the result of invoking the given function,
on that entry until all entries have been processed or
the function throws an exception.
Returns the number of key-value mappings in this map.
Returns a Collection view of the values contained in this map.
Note:
Iterator.remove
Iterator.hasNext()
Iterator.next()
Collection.remove,
Collection.removeAll,
Collection.removeIf,
Collection.retainAll and
Collection.clear
like selected operations is performed,
as it returns a Collection.
Except:
It does not support the add or addAll operations.
If the specified key is not already associated with a value ,
then associates it with the given value .
If the specified key is not already associated with a value,
and now the new value mapped with the new key is NULL ,
then it will return null.
Attempts to compute a mapping for the specified key and
its current mapped value (or null if there is no current mapping).
If the specified key is not already associated with a value
(or is mapped to null), attempts to compute its value,
using the given mapping function and
enters it into this map unless null.
If the mapping function returns null, no mapping is recorded.
If the value for the specified key is present and non-null,
attempts to compute a new mapping given the key
and its current mapped value.
If the remapping function returns null, the mapping is removed.
Returns a Set view of the mappings contained in this map.
The set is backed by the map,
so changes to the map are reflected in the set,
and vice-versa.
As entrySet()→ Is a Function that returns Set,
Hence, it call all those functions that Set contains,
Such as:
→forEach
→toArray()
→remove()
→removeIf()
→retainAll()
→removeAll()
→Stream()
→ParallelStream()
→spliterator()
→iterator()
→contains()
→containsAll()
...etc.
It does not support the add or addAll operations.
If the specified key is not already associated with a value
or is associated with null, associates it with the given non-null value.
Otherwise, replaces the associated value with the results of the given remapping function,
or removes if the result is null.
This method may be of use when combining multiple mapped values for a key.
Replaces the entry for the specified key only if it is currently mapped to some value.
Methods | Does This |
---|---|
1. Clear | It removes all of the mappings from the map. |
2.Clone | It gets a copy of this HashMap instance |
3.containsKey | Returns true if this map contains a mapping for the specified key. |
4.containsValue | Returns true if this map maps one or more keys to the specified value. |
5.forEach | Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. |
6.get(key: Key) | Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
7.getOrDefault(key: Key , defaultValue:Value) | Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. |
8.isEmpty | Returns true if this map contains no key-value mappings. |
9.KeySet | Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
10.Put | Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced. |
11.PutAll | Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had , for any of the keys currently in the specified map. |
12.Remove(key: Key) | Removes the mapping for the specified key from this map if present. |
13.Remove(key: Key, value:Value) | Removes the entry for the specified key only if it is currently mapped to the specified value. |
14.Replace(key: Key, oldValue:Value, newValue:Value) | Replaces the entry for the specified key only if currently mapped to the specified value. It replaces old value with new value. |
15.ReplaceAll(BiFunction function) | Replaces each entry's value with the result of invoking the given function, on that entry until all entries have been processed or the function throws an exception. |
16.Size() | Returns the number of key-value mappings in this map. |
17.values() | Returns a Collection view of the values contained in this map. |
18.putIfAbsent() | If the specified key is not already associated with a value , then associates it with the given value . |
19.compute(key:Key,BiFunction function) | Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
20.computeIfAbsent(key:Key, MappingFunction function) | If the specified key is not already associated with a value
(or is mapped to null), attempts to compute its value,
using the given mapping function and
enters it into this map unless null.
If the mapping function returns null, no mapping is recorded. |
21.computeIfPresent(key:Key, BiFunction function) | If the value for the specified key is present and non-null,
attempts to compute a new mapping given the key
and its current mapped value.
If the remapping function returns null, the mapping is removed. |
22.entrySet() | Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations.It does not support the add or addAll operations. |
23.merge(key:Key, value:Value, BiFunction remappingFunction) | If the specified key is not already associated with a value
or is associated with null, associates it with the given non-null value.
Otherwise, replaces the associated value with the results of the given remapping function,
or removes if the result is null.
This method may be of use when combining multiple mapped values for a key. |
24.Replace(key:Key, value:Value) | Replaces the entry for the specified key only if it is currently mapped to some value. |
Compares the specified object with this map for equality.
Returns true if the given object is also a map and the two maps represent the same mappings.
More formally, two maps m1 and m2 represent the same mappings,
if m1.entrySet().equals(m2.entrySet()).
Returns a string representation of this map.
Returns the hash code value for this map.
Methods | Does This |
---|---|
1.equals() | Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. |
2.toString() | Returns a string representation of this map. |
3.hashCode() | Returns the hash code value for this map. |
graph TD;
Map-->|implements| AbstractMap;
AbstractMap-->|extends| HashMap;
AbstractMap-->|extends| IdentityHashMap;
AbstractMap-->|extends| WeakHashMap;
AbstractMap-->|extends| TreeMap;
AbstractMap-->|extends| EnumMap;
AbstractMap-->|extends| ConcurrentHashMap;
AbstractMap-->|extends| ConcurrentSkipListMap;
AbstractMap-->|extends| Object;
ConcurrentHashMap-->|implements| ConcurrentMap;
ConcurrentSkipListMap-->|implements| ConcurrentNavigableMap;
HashMap-->|extends| LinkedHashMap;
ConcurrentMap-->|extends| Map;
Map-->|extends| SortedMap;
SortedMap-->|extends| NavigableMap;
TreeMap-->|implements| NavigableMap;
ConcurrentNavigableMap-->|extends| ConcurrentMap;
ConcurrentNavigableMap-->|extends| NavigableMap;
HashTable-->|implements|Map
sequenceDiagram
java.util.Map->>java.util.HashMap:implements
java.util.HashMap->>java.util.LinkedHashMap:extends
It is used to construct a default LinkedHashMap.
Constructs an empty insertion-ordered LinkedHashMap instance ,
with the default initial capacity (16) and load factor (0.75).
It is used to initialize a LinkedHashMap with the given capacity.
Constructs an empty insertion-ordered LinkedHashMap instance ,
with the specified initial capacity and a default load factor (0.75).
It is used to initialize both the capacity and the load factor.
Constructs an empty insertion-ordered LinkedHashMap instance,
with the specified initial capacity and load factor.
It is used to initialize both the capacity and the load factor with specified ordering mode.
Constructs an empty LinkedHashMap instance ,
with the specified initial capacity, load factor and ordering mode.
It is used to initialize the LinkedHashMap with the elements from the given Map class m.
Constructs an insertion-ordered LinkedHashMap instance ,
with the same mappings as the specified map.
The LinkedHashMap instance is created with a default load factor (0.75)
and an initial capacity sufficient to hold the mappings in the specified map.
Constructor | Description |
---|---|
LinkedHashMap() | It is used to construct a default LinkedHashMap. Constructs an empty insertion-ordered LinkedHashMap instance , with the default initial capacity (16) and load factor (0.75). |
LinkedHashMap(int capacity) | It is used to initialize a LinkedHashMap with the given capacity.Constructs an empty insertion-ordered LinkedHashMap instance , with the specified initial capacity and a default load factor (0.75). |
LinkedHashMap(int capacity, float loadFactor) | It is used to initialize both the capacity and the load factor.Constructs an empty insertion-ordered LinkedHashMap instance, with the specified initial capacity and load factor. |
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) | It is used to initialize both the capacity and the load factor with specified ordering mode.Constructs an empty LinkedHashMap instance , with the specified initial capacity, load factor and ordering mode. |
LinkedHashMap(Map m) | It is used to initialize the LinkedHashMap with the elements from the given Map class m.Constructs an insertion-ordered LinkedHashMap instance , with the same mappings as the specified map. The LinkedHashMap instance is created with a default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified map. |
Methods | Does This |
---|---|
removeEldestEntry() | It is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the elements into the map by the use of put() and putall() method. |
It is used keep a track of whether the map removes any eldest entry from the map.
So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map.
This method is generally invoked after the addition of the elements into the map,
by the use of put() and putall() method.
Eg:
If Map = {a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10}
Then, removeEldestEntry :
Size < 1 or Size ==0 → {a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10}
Size > 1 = {j=10}
Size > 2 = {i=9, j=10}
Size > 3 = {h=8, i=9, j=10}
..... etc.
sequenceDiagram
java.util.Map->>java.util.AbstractMap:implements
java.util.AbstractMap->>java.util.IdentityHashMap:extends
java.io.Serializable->>java.util.IdentityHashMap:implements
java.lang.Cloneable->>java.util.IdentityHashMap:implements
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
,Serializable, Cloneable
public class IdentityHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>
,Serializable, Cloneable
Constructs a new, empty identity hash map with a default expected maximum size (21).
It creates a new and empty identity hash map with the given specified expected maximum size.
Constructs a new, empty map with the specified expected maximum size.
Putting more than the expected number of key-value mappings into the map ,
may cause the internal data structure to grow, which may be somewhat time-consuming.
It creates a new identity hash map with the key-value pairs given in the specified map.
Constructs a new identity hash map containing the keys-value mappings in the specified map.
Constructor | Does This |
---|---|
IdentityHashMap() | Constructs a new, empty identity hash map with a default expected maximum size (21). |
IdentityHashMap(int ExpectedMaxSize) | It creates a new and empty identity hash map with the given specified expected maximum size. Constructs a new, empty map with the specified expected maximum size. Putting more than the expected number of key-value mappings into the map , may cause the internal data structure to grow, which may be somewhat time-consuming. |
IdentityHashMap(Map m) | It creates a new identity hash map with the key-value pairs given in the specified map.
Constructs a new identity hash map containing the keys-value mappings in the specified map. |
For Hash Map:
map.put("a", 1);
a is a String constant and 1 is Integer constant.
map.put(new String("a"), 2);
Here a is an object of String and 2 is an Integer constant.
But in HashMap it check key as :
map.put("a", 1).equals(map.put(new String("a"), 1));
i.e., it treats constant and object is equal as Keys are same i.e. "a".
i.e. "a".equals("a")
Which returns true , where as:
For Identity Hash Map:
map1.put("a", 1).equals(map1.put(new String("a"), 1))
Here it treats constant and object are different i.e.
"a" not equal to {new String("a")}
i.e. it uses:
"a" == {new String("a")} which is false
Hence it creates : {a=1,a=1} map
Now in Identity Hash Map:
map1.put("a", 2); will update,
1st Key which have String constant ,
i.e. : {a=2,a=1}
map1.put(new String("a"), 2); will update,
2nd Key which have String object ,
i.e. : {a=2,a=2}
While for HashMap:
map.put("a", 1);
= {a=1}
map.put(new String("a"),2}
= {a=2}
map.put("a",3}
= {a=3}
.... etc
This is the differnce between Hash Map and Identity Map.
When more than one threads access the identity hash map concurrently, and at least one of the threads structurally modifies the map, it is necessary to synchronize that map externally. (Structural modification of map is to add or delete one or more key value mappings. If we just change the value associated with a key that an instance contains already is not structural modification.)
It can be achieved by synchronizing on any object that encapsulate the map. If such object doesn't exist, map should be wrapped with the help of Collections.synchronizedMap() method. The correct time to do this is at the time of creation, in order to prevent unsynchronized access to map.
sequenceDiagram
java.util.Map->>java.util.AbstractMap:implements
java.util.AbstractMap->>java.util.WeakHashMap:extends
public class example {
public static void main(String[] args) {
example obj = new example();
obj = null;
System.gc();
}
}
obj = null
i.e. The object is garbage collected only when the variable which was strongly referenced points to null.
class ex{
public void finalize(){
System.out.println("Finalize method called");
}
}
public class example {
public static void main(String[] args) {
ex obj = new ex();
obj.finalize();
obj = null;
System.gc();//Garbage Collector
obj.finalize();//will not call finalize method and throws Null Pointer Exception
}
}
import java.lang.ref.WeakReference;
class exceptions {
void print() {
System.out.println("Print method called");
}
}
public class WeakRefexample {
public static void main(String[] args) {
// Strong Reference
exceptions obj = new exceptions();
obj.print();
// Weak Reference has explicit type class[exceptions] of Reference Object[obj]
WeakReference<exceptions> weak = new WeakReference<>(obj);
obj = null;
exceptions obj1 = weak.get();
/**
*
* get() function : It returns this reference object's referent.
* If this reference object has been cleared,
* either by the program or by the garbage collector,
* then this method returns null.
*
**/
obj1.print(); // will call print method and will not throw any exceptions
}
}
It is used to construct a default constructor of WeakHashMap.
This constructor constructs a new,
empty WeakHashMap with the default initial capacity (16)
and the default load factor (0.75).
This constructor constructs a new,
empty WeakHashMap with the given
initial capacity and
the default load factor, which is 0.75.
This constructor constructs a new, empty WeakHashMap
with the given initial capacity and the given load factor.
This constructor constructs a new WeakHashMap ,
with the same mappings as the specified Map.
Constructor | Does This |
---|---|
WeakHashMap() | It is used to construct a default constructor of WeakHashMap.This constructor constructs a new, empty WeakHashMap with the default initial capacity (16) and the default load factor (0.75). |
WeakHashMap(int initialCapacity) | This constructor constructs a new, empty WeakHashMap with the given initial capacity and the default load factor, which is 0.75. |
WeakHashMap(int initialCapacity, float loadFactor) | This constructor constructs a new, empty WeakHashMap with the given initial capacity and the given load factor. |
WeakHashMap(Map m) | This constructor constructs a new WeakHashMap , with the same mappings as the specified Map. |
Consider a Class:
class demo{
@Override
public String toString() {
return "demo";
}
public void finalize(){
System.out.println("Finalize method called");
}
}
Now:
class weakhashmap2{
public static void main(String[] args){
WeakHashMap<Object, Integer> map = new WeakHashMap<>();
demo d = new demo();
map.put(d, 1);
Now:
: Object is assigned to null :
d = null;
: And , Grabage Collector is called :
System.gc();
: Which will empty the Map as it is a Weak Reference :
: As, Weak Reference is cleared by gc :
Next:
We input Key as d and an integer 1 in the map:
map.put(d, 1);
we know d has already assigned to null hence the output: Map:{null=1}
Now we create another object say :
demo d2 = new demo();
map.put(d2, 2);
So output will be: Map:{null=1, demo=2}
: Hence it signifies the WeakReference of Key, Value pair in Weak HashMap. :
: But in Hash Map :
HashMap<Object, Integer> m = new HashMap<>();
demo d1 = new demo();
m.put(d1, 1);
:Output: Map = {demo=1}
d1 = null;//Object is referenced to null.
System.gc();//garbage collector is called.
:And again if map is called:
:It will put Object → d1 and Integer→ 1 :
:As HashMap is strongly referenced to Object → d1 and Integer→ 1:
System.out.println( m);
:Output → {demo=1}:
Now we create another object say :
demo d3 = new demo();
m.put(d3, 2);
System.out.println( m);
:Output: Map = {demo=1, demo=2}
:Note → d1,d2,d3 are different Objects of demo class :
:And are reffered to here as different keys :
:For both HashMap and WeakHashMap :
}
}
sequenceDiagram
java.util.SortedMap->>java.util.Map:extends
Comparator:
A comparison function, which imposes a total ordering on some collection of objects.
Comparators can also be used to control the order of sorted maps .
Here:
It returns the comparator used to order the keys in this map,
or null if this map uses the natural ordering of its keys.
Returns the first (lowest) key currently in this map.
Returns the last (highest) key currently in this map.
headMap(toKey:Key) :
Returns a view of the portion of this map whose keys are strictly less than toKey.
tailMap(fromKey:Key) :
Returns a view of the portion of this map whose keys are greater than and equal to fromKey.
Returns a view of the portion of this map whose keys range from fromKey, inclusive,
i.e. including fromKey and to toKey, exclusive i.e. excluding toKey.
Methods | Does This |
---|---|
1.Comparator() |
A comparison function, which imposes a total ordering on some collection of objects. Comparators can also be used to control the order of sorted maps . Here,It returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys. |
2.FirstKey() |
Returns the first (lowest) key currently in this map. |
3.LastKey() |
Returns the last (highest) key currently in this map. |
4.HeadMap(toKey:Key) |
Returns a view of the portion of this map whose keys are strictly less than toKey. |
5.TailMap(fromKey:Key) |
Returns a view of the portion of this map whose keys are greater than and equal to fromKey. |
6.SubMap(fromKey:Key, toKey:Key) |
Returns a view of the portion of this map whose keys range from fromKey, inclusive, i.e. including fromKey and to toKey, exclusive i.e. excluding toKey. |
sequenceDiagram
java.util.NavigableMap->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.Map:extends
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
Returns a key-value mapping associated with the least key greater than
or equal to the given key, or null if there is no such key.
Returns the least key greater than or equal to the given key,
or null if there is no such key.
Returns a reverse order NavigableSet view of the keys contained in this map.
The set's iterator returns the keys in descending order.
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
If the map is modified while an iteration over the set is in progress
(except through the iterator's own remove operation), the results of the iteration are undefined.
The set supports element removal, which removes the corresponding mapping from the map,
via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.
:It does not support the add or addAll operations:
Returns a reverse order view of the mappings contained in this map.
Returns a key-value mapping associated with the least key in this map,
or null if the map is empty.
Returns a key-value mapping associated with the greatest key less than
or equal to the given key, or null if there is no such key.
Returns the greatest key less than or equal to the given key,
or null if there is no such key.
Returns a view of the portion of this map whose keys are less than
(or equal to, if inclusive is true) toKey.
if true:
Returns a view of the portion of this map whose keys are equal to toKey,if inclusive is true.
if false:
Returns a view of the portion of this map whose keys are less than toKey,if inclusive is false.
Returns a key-value mapping associated with the least key strictly greater than the given key,
or null if there is no such key.
Returns the least key strictly greater than the given key, or null if there is no such key.
Returns a key-value mapping associated with the greatest key in this map,
or null if the map is empty.
Returns a key-value mapping associated with the greatest key strictly less than the given key,
or null if there is no such key.
Returns the greatest key strictly less than the given key, or null if there is no such key.
Returns a NavigableSet view of the keys contained in this map.
The set's iterator returns the keys in ascending order.
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
The set supports element removal, which removes the corresponding mapping from the map,
via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.
:It does not support the add or addAll operations:
Removes and returns a key-value mapping associated with the least key in this map,
or null if the map is empty.
Removes and returns a key-value mapping associated with the greatest key in this map,
or null if the map is empty.
Returns a view of the portion of this map whose keys range from fromKey to toKey.
If fromKey and toKey are equal, the returned map is empty
unless fromInclusive and toInclusive are both true.
Returns a view of the portion of this map whose keys are greater than,
(or equal to, if inclusive is true) fromKey.
Methods | Does This |
---|---|
1.ceilingEntry | Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key. |
2.ceilingKey | Returns the least key greater than or equal to the given key, or null if there is no such key. |
3.descendingKeySet |
Returns a reverse order NavigableSet view of the keys contained in this map. The set's iterator returns the keys in descending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
4.descendingMap | Returns a reverse order view of the mappings contained in this map. |
5.firstEntry | Returns a key-value mapping associated with the least key in this map, or null if the map is empty. |
6.floorEntry | Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key. |
7.floorKey | Returns the greatest key less than or equal to the given key, or null if there is no such key. |
8.headMap(K toKey, boolean inclusive) |
Returns a view of the portion of this map whose keys are less than
(or equal to, if inclusive is true) toKey.
if true: Returns a view of the portion of this map whose keys are equal to toKey,if inclusive is true. if false: Returns a view of the portion of this map whose keys are less than toKey,if inclusive is false. |
9.higherEntry | Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key. |
10.higherKey | Returns the least key strictly greater than the given key, or null if there is no such key. |
11.lastEntry | Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. |
12.lowerEntry | Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. |
13.lowerKey | Returns the greatest key strictly less than the given key, or null if there is no such key. |
14.navigableKeySet | Returns a NavigableSet view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. |
15.pollFirstEntry | Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. |
16.pollLastEntry | Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. |
17.SubMap( fromKey:Key, boolean fromInclusive:true/false, toKey:Key, boolean toInclusive:true/false) | Returns a view of the portion of this map whose keys range from fromKey to toKey. If fromKey and toKey are equal, the returned map is empty unless fromInclusive and toInclusive are both true. |
18.tailMap(fromKey :Key, boolean inclusive: true/false) | Returns a view of the portion of this map whose keys are greater than, (or equal to, if inclusive is true) fromKey. |
-
9." Entry pairs " returned by the methods in this class and its views represent snapshots of mappings at the time they were produced. " Entry.SetValue " is only supported when we try to change every specific values of the keys through a loop , But do not support the " Entry.setValue " method for individual entries.And they throw "Unsupported Operation Exception" .
sequenceDiagram
java.util.Map->>java.util.AbstractMap:implements
java.util.AbstractMap->>java.util.TreeMap:extends
java.util.Map->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.NavigableMap:extends
java.util.NavigableMap->>java.util.TreeMap:implements
java.io.Serializable->>java.util.TreeMap:implements
java.lang.Cloneable->>java.util.TreeMap:implements
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>,Cloneable,Serializable
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K,V> extends Map<K,V>
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>,Cloneable,Serializable
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K,V> extends Map<K,V>
It is used to construct a default constructor of TreeMap.
It is used to construct an empty tree map,
that will be sorted using the natural order of its key.
It is used to construct an empty tree-based map,
that will be sorted using the comparator.
Acc. to above eg:
TreeMap2(no:1, name:"one", value:1)
o1 and o2 are two object of TreeMap2,
Therefore Comparison:
o1.value - o2.value,
i.e,1st Diff: 1-1 = 0
TreeMap2(no:2, name:"two", value:2)
Therefore Comparison:
2nd Difference: 2-1 = 1
TreeMap2(no:3, name:"three", value:3)
o1.value: 3 - o2.value: 1 = 2
o1.value: 3 - o2.value: 2 = 1
TreeMap2(no:4, name:"four", value:4)
o1.value: 4 - o2.value: 2 = 2
o1.value: 4 - o2.value: 3 = 1
Similary:
TreeMap2(no:5, name:"five", value:5)
o1.value: 5 - o2.value: 2 = 3
o1.value: 5 - o2.value: 3 = 2
o1.value: 5 - o2.value: 4 = 1
....etc.
Hence:
if we see the comparison:
0 1 2 3 4 5 in ascending order.
Hence Result is in ascending order.
Acc. to above eg:
TreeMap2(no:1, name:"one", value:1)
o1 and o2 are two object of TreeMap2,
Therefore Comparison:
o2.value - o1.value,
i.e,1st Diff: 1-1 = 0
TreeMap2(no:2, name:"two", value:2)
Therefore Comparison:
2nd Difference: 1-2 = -1
TreeMap2(no:3, name:"three", value:3)
o2.value: 1 - o1.value: 3 = -2
o2.value: 2 - o1.value: 1 = -1
TreeMap2(no:4, name:"four", value:4)
o2.value: 2 - o1.value: 4 = -2
o2.value: 3 - o1.value: 4 = -1
Similary:
TreeMap2(no:5, name:"five", value:5)
o2.value: 2 - o2.value: 5 = -3
o2.value: 3 - o2.value: 5 = -2
o2.value: 4 - o2.value: 5 = -1
....etc.
Hence:
if we see the comparison:
-5 -4 -3 -2 -1 0 in descending order.
Hence Result is in descending order.
It is used to initialize a treemap with the entries from object of Map,
which will be sorted using the natural order of the keys.
It is used to initialize a treemap with the entries from object of SortedMap,
which will be sorted using the natural order of the keys.
It is used to initialize a treemap with the entries from object of NavigableMap,
which will be sorted using the natural order of the keys.
Note : NavigableMap extends SortedMap
And : TreeMap implements NavigableMap
Constructor | Does This |
---|---|
1.TreeMap() |
It is used to construct a default constructor of TreeMap. It is used to construct an empty tree map, that will be sorted using the natural order of its key. |
2.TreeMap(Comparator comparator) |
It is used to construct an empty tree-based map, that will be sorted using the comparator. |
3.TreeMap(Map m) |
It is used to initialize a treemap with the entries from object of Map, which will be sorted using the natural order of the keys. |
4.TreeMap(SortedMap m) |
It is used to initialize a treemap with the entries from object of SortedMap, which will be sorted using the natural order of the keys. |
5.TreeMap(NavigableMap m) |
It is used to initialize a treemap with the entries from object of NavigableMap, which will be sorted using the natural order of the keys. Note : NavigableMap extends SortedMap, And : TreeMap implements NavigableMap. |
Note: These methods are already part of Sorted Map Interface Methods, as TreeMap implements NavigableMap and NavigableMap extends SortedMap .
Suppose we have descendingKeySet() or navigableKeySet() functions:
Then:
The Set that will be produced by those function can be reserved in Set variable/object.
1. Set<Type> set_var = TreeMap.navigableKeySet();
2. Set<Type> set_var = TreeMap.descendingKeySet();
Similary for Entry say, lastEntry() or pollFirstEntry():
Then:
It calls for Maps.Entry and reserves such entries under its variable/object.
i.e.
Import java.util.Map.Entry;
Entry<Type1, Type2> entry_var = TreeMap.pollLastEntry();
or:
Map.Entry <Type1, Type2> entry_var = TreeMap.pollLastEntry();
Similary for tailMap() or subMap() type Functions:
They are always stored under the Map object/variable.
i.e.
Map<Type1, Type2> map_var = TreeMap.tailMap(fromKey:Key, inclusive: true/false);
If we want to store any key object then it can be store under it's type varibale:
Eg:
TreeMap<Float, String> treeMap = new TreeMap<>();
Float float_var = treeMap.lowerKey(4.0f);
The implementation of a TreeMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the Collections.synchronizedSortedMap method. Also it can be locked by synchronized() method and all such map objects can execute synchronized in a single thread.
sequenceDiagram
java.util.EnumMap->>java.util.AbstractMap:extends
java.util.EnumMap->>java.io.Serializable:implements
java.util.EnumMap->>java.io.Cloneable:implements
java.util.AbstractMap->>java.util.Map:implements
java.util.AbstractMap->>java.lang.Object:extends
public class EnumMap<K extends Enum<K>,V>
extends AbstractMap<K,V>
implements Serializable, Cloneable
public abstract class AbstractMap<K,V> extends Object, implements Map<K,V>
public class EnumMap<K extends Enum<K>,V>
extends AbstractMap<K,V>
implements Serializable, Cloneable
public abstract class AbstractMap<K,V> extends Object, implements Map<K,V>
Creates an empty enum map with the specified key type.
Creates an enum map with the same key type as the specified enum map,
initially containing the same mappings (if any).
It is used to create an enum map initialized from the specified map.
Constructor | Does This |
---|---|
1 . EnumMap(Class keyType) | Creates an empty enum map with the specified key type. |
2 . EnumMap(EnumMap m) | Creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any). |
3 . EnumMap(Map m) | It is used to create an enum map initialized from the specified map. |
Note :
Map.values() returns a Collection ,
Hence the return value can be stored in object/variable of Collection.
import java.util.Collection;
Collection<Type> col_var =Map.values() ;
sequenceDiagram
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
Note:
For having all the entries of a Map as a Set:
We have entrySet() function:
It can be stored in Set's variable /object by:
Either:
Set<Map.Entry<keyType, valueType>> set_var = Map.entrySet();
Or:
import java.util.Map.Entry;
Set<Entry<keyType, valueType>> set_var = Map.entrySet();
Returns an unmodifiable map containing zero mappings.
Returns an unmodifiable map containing 'N'mappings.
Returns an unmodifiable map containing keys and values,
extracted from the given entries.
The entries themselves are not stored in the map.
New Methods | Does This |
---|---|
1.Application of of() Method | Returns an unmodifiable map containing zero mappings. |
2.Application of of(1K,1V,..,nK,nV) Method | Returns an unmodifiable map containing 'N'mappings. |
3.Application of of(Map.Entry… entries) Method | Returns an unmodifiable map containing keys and values, extracted from the given entries. The entries themselves are not stored in the map. |
sequenceDiagram
java.util.concurrent.ConcurrentNavigableMap->>java.util.ConcurrentMap:extends
java.util.concurrent.ConcurrentNavigableMap->>java.util.NavigableMap:extends
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
java.util.NavigableMap->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.Map:extends
public interface ConcurrentNavigableMap<K,V> extends ConcurrentMap<K,V>
, NavigableMap<K,V>
public interface ConcurrentMap<K,V> extends Map<K,V>
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
public interface ConcurrentNavigableMap<K,V> extends ConcurrentMap<K,V>
, NavigableMap<K,V>
public interface ConcurrentMap<K,V> extends Map<K,V>
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
sequenceDiagram
java.util.concurrent.ConcurrentHashMap->>java.util.AbstractMap:extends
java.util.concurrent.ConcurrentHashMap->>java.util.concurrent.ConcurrentMap:implements
java.util.concurrent.ConcurrentHashMap->>java.io.Serializable:implements
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
java.util.AbstractMap->>java.util.Map:implements
java.util.AbstractMap->>java.lang.Object:extends
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable
public interface ConcurrentMap<K,V> extends Map<K,V>
public abstract class AbstractMap<K,V> extends Object implements Map<K,V>
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable
public interface ConcurrentMap<K,V> extends Map<K,V>
public abstract class AbstractMap<K,V> extends Object implements Map<K,V>
4.Hashtable is thread safe but give poor performance in multi-threading.Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously but Hashmap is not thread safe, hence ConcurrentHashMap is introduced in JDK 1.5. ConcurrentHashMap is thread safe ,it creates an array and each index of this array represents a HashMap. And Hashtable and HashMap both uses array and linkedlist as the data structure to store the data. Hence ,we can say, the underlined data structure for ConcurrentHashMap is Hashtable.
8.In ConcurrentHashMap, to have a update in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads as default concurrency-level of ConcurrentHashMap is 16.
- 1. CollectionView class is an abstract class of ConcurrentHashMap class which is not viable or be imported to any file . Syntax as follows:
- 2. More Over EntrySetView, KeySetView and ValuesView are "Static Final Classes" of "ConcurrentHashMap" class and are not viable or be imported to any file. Syntax as follows:
- 3. CollectionView class, EntrySetView class, KeySetView class and ValuesView class cannot be implemented directly but can be implemented through KeySetView as KeySetView , the inner class of ConcurrentHashMap class inherit those classes along with Set and Serializable interface.
- 4. The main motive of KeySetView , the inner class of ConcurrentHashMap to store the Keys of the given Map as a Set in a Variable or object created by KeySet class or ConcurrentHashMap.KeySet class.
Note : Concurrent HashMap introduced parallelism threshold parameter, which says: "How many elements are needed for an operation to be executed in parallel, synchronized".
Segment in ConcurrentHashMap : In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.Each Segment has an Array of HashMap.
If concurrency level = 10
Segment Size = 2^x >= 10
if x= 3 then 2^3 >= 10 = 8>=10 (Wrong)
Then,
x= 4 then 2^4 >= 10 = 16>=10 (Right)
Hence Segment Size = 16
Creates a new, empty map with a default initial capacity (16),
load factor (0.75) and concurrencyLevel (16)
Initial Capacity: Number of elements initially that a map can have.
if the capacity of this map is 10. It means that it can store 10 entries.
LoadFactor :
The load factor is the measure that decides when to increase the capacity of the Map.
It’s a threshold, used to control resizing of the Map.
Concurrency-Level: It is the number of threads concurrently updating the map.
The implementation performs internal sizing to try to accommodate this many threads.
Creates a new, empty map with an initial table size,
accommodating the specified number of elements,
without the need to dynamically resize.
That is: Creates a new,
empty map with the specified initial capacity,
and with default load factor (0.75) and concurrencyLevel (16)
Creates a new empty map ,
with an initial table size based on the given number of elements (initialCapacity)
and initial table density (loadFactor).
That is: Creates a new empty map ,
with the specified initial capacity and
load factor and with the default concurrencyLevel (16).
Creates a new, empty map with an initial table size,
based on the given number of elements (initialCapacity),
table density (loadFactor), a
nd number of concurrently updating threads (concurrencyLevel).
That is: Creates a new, empty map
with the specified initial capacity,
load factor, and concurrency level
Creates a new map with the same mappings as the given map.
Note: Clone() method is not implemented by ConcurrentHashMap.
It belongs to Abstract Map which is not visible to the class.
If called then it throws exception : CloneNotSupportedException.
There is a reason why Clone() method not implemented in ConcurrentHashMap.
The reason is : ConcurrentHashMap is Thread Safe and
creating a deep copy of the map would be difficult to implement .
Performs the given action for each non-null transformation of each (key, value).
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
BiFunction: Represents a function that accepts two arguments and produces a result.
Transformer: The transformer transforms the data before sending it to the Consumer.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each (key, value).
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
BiFunction: Represents a function that accepts two arguments and produces a result.
Performs the given action for each (key, value).
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each non-null transformation of each entry.
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Function: It takes one argument and produces a result.
Transformer: The transformer transforms the data before sending it to the Consumer.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each non-null transformation of each entry.
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each non-null transformation of each key.
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Function: It takes one argument and produces a result.
Transformer: The transformer transforms the data before sending it to the Consumer.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each value.
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Performs the given action for each non-null transformation of each value.
The parallelismThreshold :
It sets the number of items at which operations in a map begin to run concurrently.
It determines whether bulk operations would be executed sequentially or in parallel.
Function: It takes one argument and produces a result.
Transformer: The transformer transforms the data before sending it to the Consumer.
Consumer: It represents a functional interface which accepts
a single input argument and produces no result.
Returns a Set view of the keys in this map,
using the given common mapped value for any additions
(i.e., Collection.add and Collection.addAll(Collection)).
This is of course only appropriate if it is acceptable ,
to use the same value for all additions from this view.
Which means if a Set's object is set to Map's keyset with
its Mapped Value and if we continue to add with
Collection.add () function through set the , added
values will be refered as "Keys" of the map , automatically
gets added to Map as "Keys" gets mapped with the given Value.
Suppose we create an empty ConcurrentHashMap:
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
Set<String> set = map.keySet("1");
set.add("one");
System.out.println("Map:" + map);
Output:
Map:{one=1}
Similarly,
set = map.keySet("2");
set.add("two");
System.out.println("Map:" + map);
Output:
Map:{one=1, two=2}
....ETC.
Same for set.addAll() Functionality ,but here ,
Different keys will be assigned to Same Values.
Set<String> set2 =new HashSet<>();
set2.add("three");
set2.add("four");
set.addAll(set2);
System.out.println("Map:" + map);
Output:
Map:{one=1, two=2, three=2, four=2}
As last mapped value was 2.
Returns the number of mappings.
This method should be used instead of size . The reason is,
a ConcurrentHashMap may contain more mappings,
than can be represented as an int.
The value returned is an estimate;
the actual count may differ ,
if there are concurrent insertions or removals.
Creates a new Set backed by a ConcurrentHashMap,
from the given type to Boolean.TRUE.
Creates a new Set backed by a ConcurrentHashMap,
from the given type to Boolean.TRUE.
Returns the result of accumulating the given transformation ,
of all (key, value) pairs using the given reducer ,
to combine values, or null if none.
:Description of the Code is inside:
Returns the result of accumulating all entries ,
using the given reducer to combine values, or null if none.
Returns the result of accumulating the given transformation,
of all entries using the given reducer to combine values,
or null if none.
Returns the result of accumulating the given transformation ,
of all entries using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation ,
of all entries using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation,
of all entries using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating all keys ,
using the given reducer to combine values,
or null if none.
Returns the result of accumulating the given transformation,
of all keys using the given reducer to combine values,
or null if none.
Returns the result of accumulating the given transformation,
of all keys using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation,
of all keys using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation,
of all keys using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation of all
(key, value) pairs using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation of all (key, value) ,
pairs using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation of all
(key, value) pairs using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating all values ,
using the given reducer to combine values, or null if none.
Returns the result of accumulating the given transformation ,
of all values using the given reducer to combine values,
or null if none.
Returns the result of accumulating the given transformation,
of all values using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation,
of all values using the given reducer to combine values,
and the given basis as an identity value.
Returns the result of accumulating the given transformation of all values,
using the given reducer to combine values, and
the given basis as an identity value.
Returns a non-null result from applying the given,
search function on each (key, value), or null if none.
Upon success, further element processing is suppressed ,
and the results of any other parallel invocations ,
of the search function are ignored.
Returns a non-null result from applying the given,
search function on each entry, or null if none.
Upon success, further element processing is suppressed ,
and the results of any other parallel invocations,
of the search function are ignored.
Returns a non-null result from applying the given,
search function on each entry, or null if none.
Upon success, further element processing is suppressed ,
and the results of any other parallel invocations,
of the search function are ignored.
Returns a non-null result from applying the given,
search function on each entry, or null if none.
Upon success, further element processing is suppressed ,
and the results of any other parallel invocations,
of the search function are ignored.
Returns an enumeration of the values in this table.
Returns an enumeration of the keys in this table.
New Methods | Does This |
---|---|
1.forEach(long parallelismThreshold, BiFunction transformer, Consumer action) |
A comparison function, which imposes a total ordering on some collection of objects. Comparators can also be used to control the order of sorted maps . Here,It returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys. |
2.forEach(long parallelismThreshold, BiConsumer action) |
Performs the given action for each (key, value). |
3.forEachEntry(long parallelismThreshold, Consumer action) |
Performs the given action for each (key, value). |
4.forEachEntry(long parallelismThreshold, Function,? extends U> transformer, Consumer action) |
Performs the given action for each non-null transformation of each entry. |
5.forEachKey(long parallelismThreshold, Consumer action) |
Performs the given action for each non-null transformation of each entry. |
6.forEachKey(long parallelismThreshold, Function transformer, Consumer action) |
Performs the given action for each non-null transformation of each key. |
7.forEachKey(long parallelismThreshold, Consumer action) |
Performs the given action for each value. |
8. forEachValue(long parallelismThreshold, Functiontransformer, Consumer action) |
Performs the given action for each non-null transformation of each value. |
8. forEachValue(long parallelismThreshold, Functiontransformer, Consumer action) |
Performs the given action for each non-null transformation of each value. |
9. keySet(V mappedValue) |
Returns a Set view of the keys in this map, using the given common mapped value for any additions (i.e., Collection.add and Collection.addAll(Collection)). This is of course only appropriate if it is acceptable , to use the same value for all additions from this view. Which means if a Set's object is set to Map's keyset with its Mapped Value and if we continue to add with Collection.add () function through set the , added values will be refered as "Keys" of the map , automatically gets added to Map as "Keys" gets mapped with the given Value. |
10. MappingCount |
Returns the number of mappings. This method should be used instead of size . The reason is, a ConcurrentHashMap may contain more mappings, than can be represented as an int. The value returned is an estimate; the actual count may differ ,if there are concurrent insertions or removals. |
11. newKeySet() |
Creates a new Set backed by a ConcurrentHashMap,from the given type to Boolean.TRUE. |
12. newKeySet(int initialCapacity) |
Creates a new Set backed by a ConcurrentHashMap,from the given type to Boolean.TRUE. |
13. reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer) |
Returns the result of accumulating the given transformation ,of all (key, value) pairs using the given reducer ,to combine values, or null if none. |
14. reduceEntries(long parallelismThreshold, BiFunction,Map.Entry,? extends Map.Entry> reducer) |
Returns the result of accumulating all entries ,using the given reducer to combine values, or null if none. |
15. reduceEntries(long parallelismThreshold, Function,? extends U> transformer, BiFunction reducer) |
Returns the result of accumulating the given transformation,of all entries using the given reducer to combine values, or null if none. |
16. reduceEntriesToDouble(long parallelismThreshold, ToDoubleFunction> transformer, double basis, DoubleBinaryOperator reducer) |
Returns the result of accumulating the given transformation ,of all entries using the given reducer to combine values, and the given basis as an identity value. |
17. reduceEntriesToInt(long parallelismThreshold, ToIntFunction> transformer, int basis, IntBinaryOperator reducer) |
Returns the result of accumulating the given transformation ,of all entries using the given reducer to combine values, and the given basis as an identity value. |
18. reduceEntriesToLong(long parallelismThreshold, ToLongFunction> transformer, long basis, LongBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all entries using the given reducer to combine values, and the given basis as an identity value. |
19.reduceKeys(long parallelismThreshold, BiFunction reducer) |
Returns the result of accumulating all keys ,using the given reducer to combine values, or null if none. |
20.reduceKeys(long parallelismThreshold, Function transformer, BiFunction reducer) |
Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, or null if none. |
21. reduceKeysToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value. |
22. reduceKeysToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value. |
23.reduceKeysToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all keys using the given reducer to combine values, and the given basis as an identity value. |
24.reduceToDouble(long parallelismThreshold, ToDoubleBiFunction transformer, double basis, DoubleBinaryOperator reducer) |
Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values,and the given basis as an identity value. |
25. reduceToInt(long parallelismThreshold, ToIntBiFunction transformer, int basis, IntBinaryOperator reducer) |
Returns the result of accumulating the given transformation of all (key, value) ,pairs using the given reducer to combine values, and the given basis as an identity value. |
26. reduceToLong(long parallelismThreshold, ToLongBiFunction transformer, long basis, LongBinaryOperator reducer) |
Returns the result of accumulating the given transformation of all (key, value) pairs using the given reducer to combine values, and the given basis as an identity value. |
27. reduceValues(long parallelismThreshold, BiFunction reducer) |
Returns the result of accumulating all values ,using the given reducer to combine values, or null if none. |
28. reduceValues(long parallelismThreshold, Function transformer, BiFunction reducer) |
Returns the result of accumulating the given transformation ,of all values using the given reducer to combine values, or null if none. |
29. reduceValuesToDouble(long parallelismThreshold, ToDoubleFunction transformer, double basis, DoubleBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all values using the given reducer to combine values, and the given basis as an identity value. |
30. reduceValuesToInt(long parallelismThreshold, ToIntFunction transformer, int basis, IntBinaryOperator reducer) |
Returns the result of accumulating the given transformation,of all values using the given reducer to combine values, and the given basis as an identity value. |
31. reduceValuesToLong(long parallelismThreshold, ToLongFunction transformer, long basis, LongBinaryOperator reducer) |
Returns the result of accumulating the given transformation of all values,using the given reducer to combine values, and the given basis as an identity value. |
32.search(long parallelismThreshold, BiFunction searchFunction) |
Returns a non-null result from applying the given,search function on each (key, value), or null if none. Upon success, further element processing is suppressed ,and the results of any other parallel invocations ,of the search function are ignored. |
33. searchEntries(long parallelismThreshold, Function,? extends U> searchFunction) |
Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored. |
34. searchKeys(long parallelismThreshold, Function searchFunction) |
Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored. |
35. searchValues(long parallelismThreshold, Function searchFunction) |
Returns a non-null result from applying the given,search function on each entry, or null if none.Upon success, further element processing is suppressed ,and the results of any other parallel invocations,of the search function are ignored. |
36. Enumeration elements() |
Returns an enumeration of the values in this table. |
37. Enumeration keys() |
Returns an enumeration of the keys in this table. |
sequenceDiagram
java.util.concurrent.ConcurrentHashMap->>java.util.ConcurrentHashMap.KeySetView:InnerClass
java.util.ConcurrentHashMap.KeySetView->>java.util.concurrent.ConcurrentHashMap.CollectionView:extends
java.util.ConcurrentHashMap.KeySetView->>java.util.Set:implements
java.util.ConcurrentHashMap.KeySetView->>java.io.Serializable:implements
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
......
public static final class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable
....
}
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
......
public static final class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable
....
}
abstract static sealed class CollectionView<K,V,E>
implements Collection<E>, java.io.Serializable
permits EntrySetView, KeySetView, ValuesView
abstract static sealed class CollectionView<K,V,E>
implements Collection<E>, java.io.Serializable
permits EntrySetView, KeySetView, ValuesView
static final class EntrySetView<K,V> extends
CollectionView<K,V,Map.Entry<K,V>>
implements Set<Map.Entry<K,V>>, java.io.Serializable
static final class EntrySetView<K,V> extends
CollectionView<K,V,Map.Entry<K,V>>
implements Set<Map.Entry<K,V>>, java.io.Serializable
public static final class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable
public static final class KeySetView<K,V> extends CollectionView<K,V,K>
implements Set<K>, java.io.Serializable
static final class ValuesView<K,V> extends CollectionView<K,V,V>
implements Collection<V>, java.io.Serializable
static final class ValuesView<K,V> extends CollectionView<K,V,V>
implements Collection<V>, java.io.Serializable
sequenceDiagram
java.util.concurrent.ConcurrentSkipListMap->>java.lang.Cloneable:implements
java.util.concurrent.ConcurrentSkipListMap->>java.io.Serializable:implements
java.util.concurrent.ConcurrentSkipListMap->>java.util.concurrent.ConcurrentNavigableMap:implements
java.util.concurrent.ConcurrentSkipListMap->>java.util.AbstractMap:extends
java.util.concurrent.ConcurrentNavigableMap->>java.util.ConcurrentMap:extends
java.util.concurrent.ConcurrentNavigableMap->>java.util.NavigableMap:extends
java.util.concurrent.ConcurrentMap->>java.util.Map:extends
java.util.NavigableMap->>java.util.SortedMap:extends
java.util.SortedMap->>java.util.Map:extends
java.util.AbstractMap->>java.util.Map:implements
java.util.AbstractMap->>java.lang.Object:extends
public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable
public abstract class AbstractMap<K,V> extends Object implements Map<K,V>
public interface ConcurrentNavigableMap<K,V> extends ConcurrentMap<K,V>
, NavigableMap<K,V>
public interface ConcurrentMap<K,V> extends Map<K,V>
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
public class ConcurrentSkipListMap<K,V> extends AbstractMap<K,V>
implements ConcurrentNavigableMap<K,V>, Cloneable, Serializable
public abstract class AbstractMap<K,V> extends Object implements Map<K,V>
public interface ConcurrentNavigableMap<K,V> extends ConcurrentMap<K,V>
, NavigableMap<K,V>
public interface ConcurrentMap<K,V> extends Map<K,V>
public interface NavigableMap<K,V> extends SortedMap<K,V>
public interface SortedMap<K, V> extends Map<K, V>
Constructs a new, empty map, sorted according to the natural ordering of the keys.
Constructs a new, empty map, sorted according to the specified comparator.
Note:
1. ConcurrentSkipListMap<Key, Value> map =
new ConcurrentSkipListMap<>((a, b) -> b.compareTo(a))
2. Comparator<? super Key> comparator = map.comparator();
ConcurrentSkipListMap<Key, Value> map =
new ConcurrentSkipListMap<>(comparator)
Constructs a new, empty map, sorted according to the specified comparator.
Here Class implements Comparator interface for comparison.
Generally negative comparison : ReverseOrder
Generally positive comparison : AscendingOrder/NaturalOrder
Constructs a new, empty map, sorted according to the specified comparator.
Here Comparator object is passed inside Constructor.
Generally negative comparison : ReverseOrder
Generally positive comparison : AscendingOrder/NaturalOrder
Constructs a new, empty map, sorted according to the specified comparator.
Here Direct Comparator Class is called inside Constructor.
Comparator.reverseOrder(): Gives Reverse Order of Values
Comparator.naturalOrder(): Gives Natural Order of Values
Any negative comparison : ReverseOrder
Any positive comparison : AscendingOrder/NaturalOrder
Constructs a new map containing the same mappings as the given map,
sorted according to the natural ordering of the keys.
Constructs a new map containing the same mappings and
using the same ordering as the specified sorted map.
sequenceDiagram
java.util.HashTable->>java.util.Dictionary:extends
java.util.HashTable->>java.util.Map:implements
java.util.HashTable->>java.io.Serializable:implements
java.util.HashTable->>java.lang.Cloneable:implements