How to use Java TreeMap with Examples

Java TreeMap Example


In the tutorial, Grokonez introduces about Java TreeMap and how to use it by examples:
– Explore Java TreeMap’s hierarchy.
– Do examples with Java TreeMap method APIs

Let’s start with more details!

Related posts:
How to use Java PriorityQueue with Examples

Java TreeMap

– Java TreeMap extends AbstractMap class and implements NavigableMap interface. Here is Java TreeMap hierarchy:

Java-Tree-Map-Examples-Hierarchy

– Java TreeMap use a Red-Black tree based NavigableMap implementation.

– Java TreeMap 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.

– Java TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

– Java TreeMap’s implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

– Java TreeMap has all the functionalities of SortedMap and NavigableMap interface. A SortedMap extended with navigation methods returning the closest matches for given search targets:

+ Methods lowerEntry, floorEntry, ceilingEntry, and higherEntry return Map.Entry objects associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key, returning null if there is no such key.
+ Methods lowerKey, floorKey, ceilingKey, and higherKey return only the associated keys
+ Methods firstEntry, pollFirstEntry, lastEntry, and pollLastEntry that return and/or remove the least and greatest mappings, if any exist, else returning null.

– Java TreeMap cannot contain duplicate keys; each key can map to at most one value.

– Java TreeMap cannot contain the null key. BUT It can have null values.

Construct Java TreeMap

Setup for Examples

– Create 2 classes KeyInfo and Employee:

1. TreeMap() Constructor

Detail:

– Constructs a new, empty Java Tree Map, using the natural ordering of its keys.
– All keys inserted into the map must implement the Comparable interface.

Example:

-> Output:

Java TreeMap with Comparable Object Keys

Add Comparable interface to KeyInfo class:

– Create Java TreeMap Example:

-> Output:

2. TreeMap(comparator) Constructor

Detail:

– Constructs a new, empty tree map, ordered according to the given comparator.
– All keys inserted into the map must be mutually comparable by the given comparator.
– The comparator that will be used to order this map. If null, the natural ordering of the keys will be used.

Example: reverse order of entries

-> Output:

Create Java TreeMap Example with Object Keys using Comparator

– Implement Comparator class in Java TreeMap constructor:

– Add entries to the TreeMap:

-> Output:

3. TreeMap(Map m) Constructor

Detail:

– Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys
– All keys inserted into the new map must implement the Comparable interface.
– BigO = n*log(n) time.

Example:

– Add Comparable to KeyInfo:

– Create a Java TreeMap:

-> Output:

4. TreeMap(SortedMap m) Constructor

Detail:

– Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.
– This method runs in linear time.

Example:

+ Create SortedMap:

+ Then init a Java TreeMap:

-> Output:

Find/Search Key-Value Pair in Java TreeMap

Following the example, We use a set of TreeMap functionalities:

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.

ceilingKey(K key):
-> returns the least key greater than or equal to the given key, or null if there is no such key.

containsKey(Object key):
-> returns true if this map contains a mapping for the specified key.

containsValue(Object value):
-> returns true if this map maps one or more keys to the specified value.

firstEntry():
-> returns a key-value mapping associated with the least key in this map, or null if the map is empty.

firstKey():
-> returns the first (lowest) key currently in this map.

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.

floorKey(K key):
-> returns the greatest key less than or equal to the given key, or null if there is no such key.

get(Object key):
-> returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

lastEntry():
-> Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

lastKey():
-> Returns the last (highest) key currently in this map.

lowerEntry(K key):
-> Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.

lowerKey(K key):
-> Returns the greatest key strictly less than the given key, or null if there is no such key.

Example:

Modify/Remove Entries of Java TreeMap

List of method APIs to modify and remove entries of Java TreeMap Collection:

pollFirstEntry(): Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollLastEntry(): Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
put(K key, V value): Associates the specified value with the specified key in this map.
putAll(Map map): Copies all of the mappings from the specified map to this map.

Example:

Getting a View of Java TreeMap

List of method APIs to get a view portion of Java TreeMap:

descendingKeySet():
-> Returns a reverse order NavigableSet view of the keys contained in this map.

descendingMap():
-> Returns a Set view of the mappings contained in this map.

headMap(K toKey):
-> Returns a view of the portion of this map whose keys are strictly less than toKey.

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.

subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive):
-> Returns a view of the portion of this map whose keys range from fromKey to toKey.

subMap(K fromKey, K toKey):
-> Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

tailMap(K fromKey):
-> Returns a view of the portion of this map whose keys are greater than or equal to fromKey.

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

values():
-> Returns a Collection view of the values contained in this map.

Example:

Conclusion

We had learned how to use Java TreeMap by examples:

  • Explore Java TreeMap hierarchy.
  • How to construct Java TreeMap with difference constructors.
  • Create Java TreeMap and through almost Java TreeMap’s method APIs.

Happy Learning! See you later!

By grokonez | May 2, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*