TreeMap class methods in Java Part -III

java.util.TreeMap

A Red-Black tree-based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.


Some methods of TreeMap class


navigableKeySet()This method returns a NavigableSet view of the keys contained in this map.


pollFirstEntry()This method removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.


pollLastEntry()This method removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.


put(K, V)This method associates the specified value with the specified key in this map.


putAll(Map)This method copies all of the mappings from the specified map to this map.


putIfAbsent(K, V) 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.


remove(Object)This method removes the mapping for this key from this TreeMap if present.


remove(Object, Object)This method removes the entry for the specified key only if it is currently mapped to the specified value.


replace(K, V)This method replaces the entry for the specified key only if it is currently mapped to some value.


replaceAll(BiFunction)This method 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.


size()This method returns the number of key-value mappings in this map.


subMap(K, V)This method returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. 


subMap(K, boolean, K, boolean)This method returns a view of the portion of this map whose keys range from fromKey to toKey.


tailMap(K)This method returns a view of the portion of this map whose keys are greater than or equal to fromKey.


tailMap(K, boolean)This method returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.


toString()This method returns a string representation of this map.


values()This method returns a Collection view of the values contained in this map. 



Some more Methods of TreeMap class Part-I


Some more Methods of TreeMap class Part-II


TreeMap values() in Java

values(): This method is available in java.util.TreeMap class of Java.

Syntax:

Collection<V> java.util.TreeMap.values()

This method returns a Collection view of the values contained in this map. The collection's iterator returns the values in ascending order of the corresponding keys.

Parameters: NA

Returns: a collection view of the values contained in this map,sorted in ascending key order.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMapvalues {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        System.out.println(treeMap.values());

    }
}

Output:

[Hello, C++, Java, Program, Program]


TreeMap toString() in Java

toString(): This method is available in java.util.TreeMap class of Java.

Syntax:

String java.util.AbstractMap.toString()

This method returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces( "{}"}).

Parameters: NA

Returns: a string representation of this map.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMaptoString {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        System.out.println(treeMap.toString());

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program, 25=Program}


TreeMap tailMap(K, boolean) in Java

tailMap(K, boolean): This method is available in java.util.TreeMap class of Java.

Syntax:

NavigableMap<K, V> java.util.TreeMap.tailMap(K fromKey, boolean inclusive)

This method takes two arguments. This method returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.

Note: The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.

Parameters: Two parameters are required for this method.

fromKey: low end point of the keys in the returned map.

inclusive: true if the low end point is to be included in the returned view.

Returns: view of the portion of this map whose keys are greater than(or equal to, if inclusive is true) fromKey.

Throws:

1. ClassCastException - if fromKey is not compatible with this map's comparator.

2. NullPointerException - if fromKey is null and this map uses natural ordering, or its comparator does not permit null keys.

3. IllegalArgumentException - if this map itself has a restricted range, and fromKey lies outside the bounds of the range.

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMaptailMap2 {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = 2;
        boolean inclusive = true;
        System.out.println(treeMap.tailMap(fromKey,
inclusive));

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program, 25=Program}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMaptailMap2 {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = null;
        boolean inclusive = true;
        System.out.println(treeMap.tailMap(fromKey,
inclusive));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap$NavigableSubMap.<init>(TreeMap.java:1644) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1210)


TreeMap tailMap(K) in Java

tailMap(K): This method is available in java.util.TreeMap class of Java.

Syntax:

SortedMap<K, V> java.util.TreeMap.tailMap(K fromKey)

This method takes one argument. This method returns a view of the portion of this map whose keys are greater than or equal to fromKey.

Note: The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.

Parameters: One parameter is required for this method.

fromKey: low end point (inclusive) of the keys in the returned map.

Returns: a view of the portion of this map whose keys are greater than or equal to fromKey.

Throws:

1. ClassCastException - if fromKey is not compatible with  this map's comparator.

2. NullPointerException - if fromKey is null and this map uses natural ordering, or its comparator does not permit null keys.

3. IllegalArgumentException - if this map itself has a restricted range, and fromKey lies outside the bounds of the range

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMaptailMap {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = 2;

        System.out.println(treeMap.tailMap(fromKey));

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program, 25=Program}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMaptailMap {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = null;

        System.out.println(treeMap.tailMap(fromKey));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap$NavigableSubMap.<init>(TreeMap.java:1644) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1210) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1245)


TreeMap subMap(K, boolean, K, boolean) in Java

subMap(K, boolean, K, boolean): This method is available in java.util.TreeMap class of Java.

Syntax:

NavigableMap<K, V> java.util.TreeMap.subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)

This method takes four arguments. This method 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.

Note: The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.

Parameters: Four parameters are required for this method.

fromKey: low end point of the keys in the returned map.

fromInclusive: true if the low end point is to be included in the returned view.

toKey: high end point of the keys in the returned map.

toInclusive: true if the high end point is to be included in the returned view.

Returns: a view of the portion of this map whose keys range from fromKey to toKey.

Throws:

1. ClassCastException - if fromKey and toKey cannot be compared to one another using this map's comparator.

2. NullPointerException - if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys.

3. IllegalArgumentException - if fromKey is greater than toKey; or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range.

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapsubMap2 {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = 2, toKey = 23;
        boolean fromInclusive = true, toInclusive = true;

        System.out.println(treeMap.subMap(fromKey,
fromInclusive, toKey, toInclusive));

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMapsubMap2 {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = null, toKey = 23;
        boolean fromInclusive = true, toInclusive = true;

        System.out.println(treeMap.subMap(fromKey,
fromInclusive, toKey, toInclusive));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap$NavigableSubMap.<init>(TreeMap.java:1640) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.subMap(TreeMap.java:1182)


TreeMap subMap(K, V) in Java

subMap(K, V): This method is available in java.util.TreeMap class of Java.

Syntax:

SortedMap<K, V> java.util.TreeMap.subMap(K fromKey, V toKey)

This method takes two arguments. This method returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. 

Note: The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.

Parameters: Two parameters are required for this method.

fromKey: low end point (inclusive) of the keys in the returned map.

toKey: high end point (exclusive) of the keys in the returned map.

Returns: a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

Throws:

1. ClassCastException - if fromKey and toKeycannot be compared to one another using this map's comparator.

2. NullPointerException - if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys.

3. IllegalArgumentException - if fromKey is greater than toKey; or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapsubMap {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = 2, toKey = 23;

        System.out.println(treeMap.subMap(fromKey, toKey));

    }
}

Output:

{2=Hello, 6=C++, 11=Java}


Approach 2: NullPointerException

Java

import java.util.TreeMap;

public class TreeMapsubMap {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer fromKey = null, toKey = 23;

        System.out.println(treeMap.subMap(fromKey, toKey));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap$NavigableSubMap.<init>(TreeMap.java:1640) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.subMap(TreeMap.java:1182) at java.base/java.util.TreeMap.subMap(TreeMap.java:1223)


TreeMap size() in Java

size(): This method is available in java.util.TreeMap class of Java.

Syntax:

int java.util.TreeMap.size()

This method returns the number of key-value mappings in this map.

Parameters: NA

Returns: the number of key-value mappings in this map.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMapsize {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        System.out.println(treeMap.size());

    }
}

Output:

5


TreeMap replaceAll(BiFunction) in Java

replaceAll(BiFunction): This method is available in java.util.TreeMap class of Java.

Syntax:

void java.util.TreeMap.replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

This method takes one argument. This method 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.

Parameters: One parameter is required for this method.

function: the function to apply to each entry.

Returns: NA

Exceptions: NA

Approach

Java

import java.util.TreeMap;
import java.util.function.BiFunction;

public class TreeMapreplaceAll {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        BiFunction<? super Integer, ? super String,
? extends String> function = (a, b) -> a + b;

        treeMap.replaceAll(function);

        System.out.println(treeMap);

    }
}

Output:

{2=2Hello, 6=6C++, 11=11Java, 23=23Program, 25=25Program}


TreeMap replace(K, V) in Java

replace(K, V): This method is available in java.util.TreeMap class of Java.

Syntax:

String java.util.TreeMap.replace(K key, V value)

This method takes two arguments. This method replaces the entry for the specified key only if it is currently mapped to some value.

Parameters: Two parameters are required or this method.

key: key with which the specified value is associated.

value: value to be associated with the specified key.

Returns: the previous value associated with the specified key, or null if there was no mapping for the key.

Exceptions: NA

Approach

Java

import java.util.TreeMap;

public class TreeMapreplace {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer key = 11;
        String value = "World";

        System.out.println(treeMap.replace(key, value));

    }
}

Output:

Java