Net-informations.com
SiteMap  | About    

Java The TreeMap Class

TreeMap class implements Map interface similar to HashMap class. It maintains its entries in ascending order, sorted according to the keys natural ordering, or according to a Comparator depends on constructor argument. Unlike LinkedHashMap and HashMap, TreeMap does not use hashing for storing keys. It uses a data structure called Red-Black tree.

Java TreeMap and Red-Black tree algorithm

A red–black tree is a kind of self-balancing binary search tree which has the following red-black properties:

How to Java TreeMap

TreeMap implementation is not synchronized . If multiple threads access a TreeMap concurrently, and at least one of the threads modifies the TreeMap structurally, it should be synchronized externally. The TreeMap class is perfect for traversing the keys in a sorted order. The keys can be sorted using the Comparable interface or the Comparator interface. You can specify Sorting order while Creating TreeMap by providing an explicit Comparator to TreeMap. Moreover, it provides the methods firstKey() and lastKey() for returning the first and last keys in the map, and headMap(toKey) and tailMap(fromKey) for returning a portion of the map whose keys are less than toKey and greater than or equal to fromKey.

The following Java program illustrates several of the methods supported by this TreeMap collection Framework:









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.