Saturday, January 11, 2020

TreeMap

TreeMap(Java Collections)

An object of Map represents a group of objects, each of which is associated with a key. Like HashMap, TreeMap allows us to store values associated with the keys. A Map cannot contain duplicate keys. You can get the object from a Map using a key.TreeMap provides a guarantee of ordering(ascending, natural or provided) as TreeMap implements SortedMap.TreeMap does not allow null key but null values are allowed. TreeMap offers logarithmic time access for the general method to get, put and contains values.


TreeMap in Java Collections

Example
import java.util.Map.Entry;
import java.util.TreeMap;

public class TreeMapDemo {
public static void main(String[] a)
{
      TreeMap<Integer, String> tm=new TreeMap<>();
      tm.put(1, "RED");
      tm.put(19, "BLUE");
      tm.put(20, "BLACK");
      tm.put(7, "ORANGE");
      tm.put(20, "RED");
      tm.put(31, "PURPLE");//sorted
      for(Entry<Integer, String> e:tm.entrySet())
      {
            System.out.println(e.getKey()+"\t"+e.getValue());
      }
}
}
Output:
1 RED
7 ORANGE
19 BLUE
20 RED
31 PURPLE


Another Example
import java.util.TreeMap;
class CustomKey implements Comparable<CustomKey>{
      int a;
      CustomKey(int a){this.a=a;}
      @Override
      public int compareTo(CustomKey o) {
            return this.a-o.a;
      }
}
public class TreeMapDemo {//TreeMap Example
      public static void main(String[] args) {
            TreeMap<CustomKey, String> color=new TreeMap<>();
            color.put(new CustomKey(2),"RED");
            color.put(new CustomKey(51),"BLUE");
            color.put(new CustomKey(19),"ORANGE");
            color.put(new CustomKey(1),"PURPLE");
            color.put(new CustomKey(36),"MAGENTA");
            for(java.util.Map.Entry<CustomKey, String> s:color.entrySet())
            {
                  System.out.println("Key: "+s.getKey().a+"\t value : "+s.getValue());
            }
           
      }
}
Output:
Key: 1 value : PURPLE
Key: 2 value : RED
Key: 19 value : ORANGE
Key: 36 value : MAGENTA

Key: 51 value : BLUE




Methods

public boolean containsKey(Object key)

This method returns true if this map contains a mapping for the defined key.

public void clear()

This method removes all of the mappings from this map. The map will be empty after this call returns.

public boolean containsKey(Object key)

This method returns true if this map contains a mapping for the defined key.

public boolean containsValue(Object value)

This method returns true if this map maps one or more keys to the defined value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations.

public Set<Map.Entry<K,V>> entrySet()

This method returns a Set view of the mappings contained in this map.
The set's iterator returns the entries in ascending key order. The set's spliterator is late-binding, fail-fast, and additionally reports Spliterator.SORTED and Spliterator.ORDERED with an encounter order that is ascending key order.

public V get(Object key)

This method returns the value to which the defined key is mapped, or null if this map contains no mapping for the key.
More formally, if this map contains a mapping from a key k to a value v such that key compares equal to k according to the map's ordering, then this method returns v; otherwise, it returns null.
This method returns a value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

public V put(K key, V value)

 This method associates the defined value with the defined key in this map. If the map previously contained a mapping for the key, the old value is replaced.

public void putAll(Map<? extends K,? extends V> map)

This method copies all of the mappings from the defined map to this map. These mappings replace any mappings that this map had for any of the keys currently in the defined map.

boolean isEmpty()

This method returns true if this map contains no key-value mappings.

public K firstKey()

This method returns the first (lowest) key currently in this map.

public void forEach(BiConsumer<? super K,? super V> action)

This method performs the given action for each entry in this map until all entries have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of entry set iteration (if an iteration order is specified.)Exceptions thrown by the action are relayed to the caller.

Video Tutorial