WeakHashMap, SortedMap, TreeMap in Java Map

There are also WeakHashMap, SortedMap, TreeMap present in Java Map. 

WeakHashMap, SortedMap, TreeMap are also the same as HashMap in Java Map with some differences as below

WeakHashMap

Following is the difference between HashMap and WeakHashMap.

  • In the case of HashMap even though the object doesn’t have any reference it is not eligible for Garbage Collection if it is associated with HashMap i.e. HashMap dominates Garbage Collector
  • But in the case of WeakHashMap, if the object doesn’t contain any references it is eligible for it even though the object is associated with a weak hash map i.e. Garbage Collector dominates WeakHashMap.

We can create WeakHashMap by using the following constructors.

  1. public WeakHashMap(): Creates a new, empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
  2. public WeakHashMap(int initialCapacity): Creates a new, empty WeakHashMap with the given initial capacity and the default load factor (0.75).
  3. public WeakHashMap(int initialCapacity, float loadFactor): Creates a new, empty WeakHashMap with the given initial capacity and the given load factor.
  4. public WeakHashMap(Map<? extends K,? extends V> m): Creates a new WeakHashMap with the same mappings as the specified map.

Example for WeakHashMap:

In the below example temp object is not eligible for Garbage Collection because if it is associated with HashMap in this case output will be:

{temp=ABCD}

{temp=ABCD}

But if we use WeakHashMap instead of HashMap then the temp object is eligible for Garbage Collection  in this case output is :

{temp=ABCD}

finalize method call

{}

Java Code
import java.util.WeakHashMap;

public class Test {
public static void main(String[] args) throws Exception{
WeakHashMap<TempClass, String> map = new WeakHashMap<>();
TempClass temp = new TempClass();
map.put(temp, “ABCD”);
System.out.println(map);
temp = null; // removing the reference for previous object
System.gc();
Thread.sleep(3000);
System.out.println(map);
}
}

class TempClass {
public String toString() {
return “temp”;
}

public void finalize() {
System.out.println(“finalize method call”);
}
}
Output:
{temp=ABCD}
finalize method call
{}

SortedMap

  1. A sorted map is an  Interface. It is a child interface of Map.
  2. If we want to represent a group of key-value pairs according to some sorting order of keys then we should go for SortedMap.
  3. Sorting is based on the key but not based on value.

Following are the methods specific to SortedMap

  1. Comparator<? super K> comparator(): Returns the comparator used to order the keys in this map, or null if uses the natural ordering.
  2. Set<Map.Entry<K,V>> entrySet(): Returns a Set view of the mappings contained in this map.
  3. K firstKey(): Returns the first (lowest) key currently in this map.
  4. SortedMap<K, V> headMap(K toKey): Returns a view of the portion of this map whose keys are strictly less than toKey.
  5. Set<K> keySet(): Returns a Set view of the keys contained in this map.
  6. K lastKey(): Returns the last (highest) key currently in this map.
  7. SortedMap<K, V> subMap(K fromKey, K toKey): Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
  8. SortedMap<K, V> tailMap(K fromKey): Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
  9. Collection<V> values(): Returns a Collection view of the values contained in this map.

TreeMap

  1. This is a Class whose underlying data structure for TreeMap is RED-BLOCK Tree.
  2. Insertion order is not preserved and it is based on some sorting order of keys.
  3. Duplicate keys are not allowed but values can be duplicated.
  4. If we are depending on default natural sorting order then keys should be Homogeneous and Comparable Otherwise we will get a Runtime Exception: ClassCastException If we are defining our own sorting by Comparator then keys need not be Homogeneous and Comparable we can take Heterogeneous non-comparable objects also. Whether we are depending on default natural sorting order or Customized sorting order there are no restrictions for values we can take Heterogeneous non-comparable objects also.
  1. Null Acceptance: null key not allowed from 1.7v onwards even once. For values we can use null any number of times there is no restriction whether it is 1.6v or 1.7v.

Constructors for TreeMap are as follows.

  1. public TreeMap(): Creates a new, empty TreeMap , using the natural ordering of its keys.
  2. public TreeMap(Comparator<? super K> comparator): Creates a new, empty TreeMap, ordered according to the given comparator.
  3. public TreeMap(Map<? extends K,? extends V> m): Creates a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.
  4. public TreeMap(SortedMap<K,? extends V> m): Creates a new tree map containing the same mappings and using the same ordering as the specified sorted map.

Following is an example for SortedMap and TreeMap using the above constructors and how to use methods specific to SortedMap.

Java Code
import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;

public class Test {
public static void main(String[] args) throws Exception{
SortedMap<Integer, String> map = new TreeMap<>();
map.put(3, “ABCD”);
map.put(67, “GSFE”);
map.put(45, “KDGF”);
map.put(22, “HJDK”);
map.put(10, “IEKD”);

System.out.println(“Original Map: “+ map);
System.out.println(“map comparator object: ” + map.comparator());
System.out.println(“map first key: ” + map.firstKey());
System.out.println(“headMap for map: ” + map.headMap(10));
System.out.println(“tailMap for map: ” + map.tailMap(22));

System.out.println(“————————“);
// by using Comparator reverse sorting order
SortedMap<Integer, String> map2 = new TreeMap<Integer, String>(new UserComparator());
map2.put(3, “ABCD”);
map2.put(67, “GSFE”);
map2.put(45, “KDGF”);
map2.put(22, “HJDK”);
map2.put(10, “IEKD”);
System.out.println(“Original Map2: “+ map2);
System.out.println(“map2 comparator object: ” +map2.comparator());
System.out.println(“map2 first key: ” + map2.firstKey());
System.out.println(“headMap for map2: ” + map2.tailMap(10));
System.out.println(“tailMap for map2: ” + map2.tailMap(22));
}
}

class UserComparator implements Comparator<Object>{
@Override
// here we are doing reverse sorting order
public int compare(Object o1, Object o2) {
Integer i1 = (Integer) o1;
Integer i2 = (Integer) o2;
if(i1>i2)
return -1;
else if(i1<i2)
return 1;
else return 0;
}
}
Output:
Original Map: {3=ABCD, 10=IEKD, 22=HJDK, 45=KDGF, 67=GSFE}
map comparator object: null
map first key: 3
headMap for map: {3=ABCD}
tailMap for map: {22=HJDK, 45=KDGF, 67=GSFE}
————————
Original Map2: {67=GSFE, 45=KDGF, 22=HJDK, 10=IEKD, 3=ABCD}
map2 comparator object: UserComparator@2401f4c3
map2 first key: 67
headMap for map2: {10=IEKD, 3=ABCD}
tailMap for map2: {22=HJDK, 10=IEKD, 3=ABCD}

Following are the methods specific to TreeMap

  1. Map.Entry<K,V> ceilingEntry(K key): 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. K ceilingKey(K key): Returns the least key greater than or equal to the given key, or null if there is no such key.
  3. void clear(): Removes all of the mappings from the map.
  4. Object clone(): Returns a shallow copy of this TreeMap instance.
  5. Comparator<? super K> comparator(): Returns the comparator used to order the keys in the map, or null if the map uses the natural ordering of its keys.
  6. boolean containsKey(Object key): Returns true if the map contains a mapping for the specified key.
  7. boolean containsValue(Object value): Returns true if the map maps one or more keys to the specified value.
  8. NavigableSet<K> descendingKeySet(): Returns a reverse order NavigableSet view of the keys contained in the map.
  9. NavigableMap<K,V> descendingMap(): Returns a reverse order view of the mappings contained in the map.
  10. Set<Map.Entry<K,V>> entrySet(): Returns a Set view of the mappings contained in the map.
  11. Map.Entry<K,V> firstEntry(): Returns a key-value mapping associated with the least key in the map, or null if the map is empty.
  12. K firstKey(): Returns the first (lowest) key currently in the map.
  13. Map.Entry<K,V> floorEntry(K key): 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.
  14. K floorKey(K key): Returns the greatest key less than or equal to the given key, or null if there is no such key.
  15. V get(Object key): Returns the value to which the specified key is mapped, or null if the map contains no mapping for the key.
  16. SortedMap<K,V> headMap(K toKey): Returns a view of the portion of the map whose keys are strictly less than toKey.
  17. NavigableMap<K,V> headMap(K toKey, boolean inclusive): Returns a view of the portion of the map whose keys are less than (or equal to, if inclusive is true) toKey.
  18. Map.Entry<K,V> higherEntry(K key): Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
  19. K higherKey(K key): Returns the least key strictly greater than the given key, or null if there is no such key.
  20. Set<K> keySet(): Returns a Set view of the keys contained in the map.
  21. Map.Entry<K,V> lastEntry(): Returns a key-value mapping associated with the greatest/last key in the map, or null if the map is empty.
  22. K lastKey(): Returns the last (highest) key currently in the map.
  23. Map.Entry<K,V> lowerEntry(K key): Returns a key-value mapping associated with the greatest/last key strictly less than the given key, or null if there is no such key.
  24. K lowerKey(K key): Returns the greatest/last key strictly less than the given key, or null if there is no such key.
  25. NavigableSet<K> navigableKeySet(): Returns a NavigableSet view of the keys contained in the map.
  26. Map.Entry<K,V> pollFirstEntry(): Removes and returns a key-value mapping associated with the least key in the map, or null if the map is empty.
  27. Map.Entry<K,V> pollLastEntry(): Removes and returns a key-value mapping associated with the greatest key in the map, or null if the map is empty.
  28. V put(K key, V value): Associates the specified value with the specified key in the map.
  29. void putAll(Map<? extends K,? extends V> map): Copies all of the mappings from the specified map to the map.
  30. V remove(Object key): Removes the mapping for this key from this TreeMap if present.
  31. int size(): Returns the number of key-value mappings in the map.
  32. NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive): Returns a view of the portion of the map whose keys range from fromKey to toKey.
  33. SortedMap<K,V> subMap(K fromKey, K toKey): Returns a view of the portion of the map whose keys range from fromKey, inclusive, to toKey, exclusive.
  34. SortedMap<K,V> tailMap(K fromKey): Returns a view of the portion of the map whose keys are greater than or equal to fromKey.
  35. NavigableMap<K,V> tailMap(K fromKey, boolean inclusive): Returns a view of the portion of the map whose keys are greater than (or equal to, if inclusive is true) fromKey.
  36. Collection<V> values(): Returns a Collection view of the values contained in the map.

-A blog by Shwetali Khambe

Related Posts