Java TreeMap is a class that implements the Map interface and provides a tree-based implementation of a Map. It is similar to HashMap, but with one major difference: the keys in a TreeMap are sorted in natural order or according to a specified comparator.
Some of the key features of TreeMap are:
- Keys are sorted in natural order (or according to a specified comparator).
- TreeMap is not thread-safe, meaning it should be used only in single-threaded environments or with appropriate synchronization.
- It provides O(log n) time complexity for insertion, deletion, and search operations.
- TreeMap allows null values but not null keys.
To create a TreeMap, you can use one of its constructors. For example:
TreeMap<String, Integer> map = new TreeMap<>();
This creates an empty TreeMap that will store String keys and Integer values, sorted in natural order.
You can also create a TreeMap with a specified Comparator. For example:
TreeMap<String, Integer> map = new TreeMap<>(Comparator.reverseOrder());
This creates a TreeMap that will store String keys and Integer values, sorted in reverse order.
Some of the methods provided by TreeMap are:
- put(K key, V value): Inserts the specified key-value pair into the map.
- get(Object key): Returns the value associated with the specified key.
- remove(Object key): Removes the key-value pair associated with the specified key.
- firstKey(): Returns the first (lowest) key currently in the map.
- lastKey(): Returns the last (highest) key currently in the map.
- keySet(): Returns a set of all the keys in the map.
Overall, TreeMap is a useful data structure when you need a map with keys sorted in a specific order. However, it is slower than HashMap for most operations, so it’s not the best choice when performance is a concern.
TreeMap class declaration:
The TreeMap class in Java is declared as follows:
public class TreeMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V>, Cloneable, Serializable
The class is generic, and takes two type parameters, K and V, which represent the key and value types of the map, respectively.
The TreeMap class extends the AbstractMap class and implements the NavigableMap interface, as well as the Cloneable and Serializable interfaces.
The NavigableMap interface extends the SortedMap interface and provides methods for navigation and retrieval of entries based on the keys. The SortedMap interface, in turn, extends the Map interface and provides methods for accessing and manipulating key-value pairs in a sorted order.
The TreeMap class also provides several constructors, including one that takes no arguments and creates an empty TreeMap with the natural ordering of keys. Another constructor allows you to specify a custom Comparator to order the keys in the TreeMap. Additionally, the class provides a number of methods for accessing, adding, and removing elements from the TreeMap, as well as other operations such as submap and headMap, which allow you to obtain a view of a subset of the keys in the map.
TreeMap class Parameters:
The TreeMap class in Java is parameterized by two types: K and V. These type parameters specify the types of the keys and values that can be stored in the TreeMap, respectively.
The first type parameter, K, represents the type of the keys that will be used to access the values in the map. Keys in a TreeMap must be mutually comparable, meaning that they must implement the Comparable interface or a custom Comparator must be provided to order the keys in the map.
The second type parameter, V, represents the type of the values that will be stored in the map. Values in a TreeMap can be of any type, including primitive types and reference types.
When creating a TreeMap, you must specify the types of the keys and values that will be stored in the map. For example, to create a TreeMap that stores String keys and Integer values, you would use the following code:
TreeMap<String, Integer> map = new TreeMap<>();
This creates a new TreeMap instance that stores String keys and Integer values.
Note that the TreeMap class is a generic class, which means that type parameters are used to specify the types of objects that can be stored in the map. This provides type safety and allows the compiler to detect and report type errors at compile-time rather than at runtime.
Constructors of Java TreeMap class:
The TreeMap class in Java provides several constructors to create new TreeMap instances. These constructors are:
TreeMap()
: Creates an empty TreeMap instance with the natural ordering of keys.TreeMap(Comparator<? super K> comparator)
: Creates an empty TreeMap instance with the given Comparator to order the keys.TreeMap(Map<? extends K, ? extends V> map)
: Creates a new TreeMap instance with the same mappings as the given Map, sorted according to the natural ordering of the keys.TreeMap(SortedMap<K, ? extends V> map)
: Creates a new TreeMap instance with the same mappings as the given SortedMap, sorted according to the same ordering as the input map.
All of these constructors create a new TreeMap instance with specified initial mappings or ordering of keys. The first constructor creates an empty TreeMap with the natural ordering of keys. The second constructor creates an empty TreeMap with the given Comparator to order the keys. The third constructor creates a new TreeMap instance with the same mappings as the given Map, sorted according to the natural ordering of the keys. The fourth constructor creates a new TreeMap instance with the same mappings as the given SortedMap, sorted according to the same ordering as the input map.
Here is an example of using the second constructor to create a TreeMap with a custom ordering of keys:
TreeMap<String, Integer> map = new TreeMap<>(Comparator.reverseOrder());
This creates an empty TreeMap that orders its keys in reverse natural order.
Note that TreeMap is a generic class, so the type parameters K and V must be specified when creating a new TreeMap instance.
Methods of Java TreeMap class:
The TreeMap class in Java provides a variety of methods for manipulating and accessing the contents of the TreeMap. Some of the most commonly used methods are:
put(K key, V value)
: Inserts the given key-value pair into the TreeMap.get(Object key)
: Returns the value associated with the given key in the TreeMap, or null if the key is not present.remove(Object key)
: Removes the key-value pair associated with the given key from the TreeMap.size()
: Returns the number of key-value pairs in the TreeMap.containsKey(Object key)
: Returns true if the TreeMap contains the given key, and false otherwise.containsValue(Object value)
: Returns true if the TreeMap contains the given value, and false otherwise.firstKey()
: Returns the first (lowest) key in the TreeMap.lastKey()
: Returns the last (highest) key in the TreeMap.keySet()
: Returns a Set view of the keys contained in the TreeMap.values()
: Returns a Collection view of the values contained in the TreeMap.entrySet()
: Returns a Set view of the key-value pairs contained in the TreeMap.subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)
: Returns a view of the portion of the TreeMap whose keys range from fromKey to toKey.headMap(K toKey, boolean inclusive)
: Returns a view of the portion of the TreeMap whose keys are less than (or equal to, if inclusive is true) toKey.tailMap(K fromKey, boolean inclusive)
: Returns a view of the portion of the TreeMap whose keys are greater than (or equal to, if inclusive is true) fromKey.
These are just a few examples of the many methods provided by the TreeMap class. The class also provides methods for iterating over the keys and values in the TreeMap, as well as various methods for modifying the TreeMap (such as clear() and putAll()). Additionally, because TreeMap implements the NavigableMap interface, it provides a rich set of methods for navigating and retrieving entries based on the keys.
Java TreeMap Example:
Here’s an example of how to use the TreeMap class in Java:
import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { // create a TreeMap with String keys and Integer values TreeMap<String, Integer> map = new TreeMap<>(); // insert some key-value pairs into the map map.put("Alice", 42); map.put("Bob", 37); map.put("Charlie", 29); map.put("Dave", 53); map.put("Eve", 24); // print the contents of the map System.out.println("Contents of the TreeMap:"); System.out.println(map); // get the value associated with a specific key String key = "Bob"; Integer value = map.get(key); System.out.println("The value associated with " + key + " is " + value); // remove a key-value pair from the map key = "Charlie"; map.remove(key); System.out.println("After removing " + key + ", the map is:"); System.out.println(map); // iterate over the keys in the map System.out.println("Keys in the TreeMap:"); for (String k : map.keySet()) { System.out.println(k); } // iterate over the values in the map System.out.println("Values in the TreeMap:"); for (Integer v : map.values()) { System.out.println(v); } } }
Output:
Contents of the TreeMap: {Alice=42, Bob=37, Charlie=29, Dave=53, Eve=24} The value associated with Bob is 37 After removing Charlie, the map is: {Alice=42, Bob=37, Dave=53, Eve=24} Keys in the TreeMap: Alice Bob Dave Eve Values in the TreeMap: 42 37 53 24
In this example, we create a TreeMap with String keys and Integer values, and insert some key-value pairs into the map using the put()
method. We then print the contents of the map using the toString()
method, and retrieve the value associated with a specific key using the get()
method.
Next, we remove a key-value pair from the map using the remove()
method, and print the updated contents of the map. We then iterate over the keys and values in the map using the keySet()
and values()
methods, respectively, and print them to the console.
Java TreeMap Example: remove()
Sure, here’s an example of how to use the remove()
method in a TreeMap:
import java.util.TreeMap; public class TreeMapRemoveExample { public static void main(String[] args) { // create a TreeMap with Integer keys and String values TreeMap<Integer, String> map = new TreeMap<>(); // insert some key-value pairs into the map map.put(1, "Alice"); map.put(2, "Bob"); map.put(3, "Charlie"); map.put(4, "Dave"); // print the contents of the map System.out.println("Before removing a key-value pair:"); System.out.println(map); // remove a key-value pair from the map int keyToRemove = 2; String removedValue = map.remove(keyToRemove); // print the removed key-value pair System.out.println("Removed key-value pair: " + keyToRemove + " => " + removedValue); // print the updated contents of the map System.out.println("After removing a key-value pair:"); System.out.println(map); } }
Output:
Before removing a key-value pair: {1=Alice, 2=Bob, 3=Charlie, 4=Dave} Removed key-value pair: 2 => Bob After removing a key-value pair: {1=Alice, 3=Charlie, 4=Dave}
In this example, we create a TreeMap with Integer keys and String values, and insert some key-value pairs into the map using the put()
method. We then print the contents of the map using the toString()
method.
Next, we remove a key-value pair from the map using the remove()
method, passing in the key we want to remove as an argument. We store the removed value in a variable for later use. We then print the removed key-value pair to the console.
Finally, we print the updated contents of the map using the toString()
method. The removed key-value pair is no longer present in the map.
Java TreeMap Example: NavigableMap
Sure, here’s an example of how to use the NavigableMap
interface, which is implemented by the TreeMap
class, to perform navigation operations on a sorted map:
import java.util.NavigableMap; import java.util.TreeMap; public class TreeMapNavigableMapExample { public static void main(String[] args) { // create a TreeMap with Integer keys and String values TreeMap<Integer, String> map = new TreeMap<>(); // insert some key-value pairs into the map map.put(1, "Alice"); map.put(2, "Bob"); map.put(3, "Charlie"); map.put(4, "Dave"); map.put(5, "Eve"); // print the contents of the map System.out.println("Contents of the TreeMap:"); System.out.println(map); // create a NavigableMap view of the map NavigableMap<Integer, String> navigableMap = map.descendingMap(); // print the contents of the NavigableMap System.out.println("Contents of the NavigableMap:"); System.out.println(navigableMap); // get the first key in the map int firstKey = map.firstKey(); System.out.println("The first key in the map is " + firstKey); // get the last key in the map int lastKey = map.lastKey(); System.out.println("The last key in the map is " + lastKey); // get the greatest key less than or equal to a given key int key1 = 3; int floorKey = map.floorKey(key1); System.out.println("The greatest key less than or equal to " + key1 + " is " + floorKey); // get the least key greater than or equal to a given key int key2 = 3; int ceilingKey = map.ceilingKey(key2); System.out.println("The least key greater than or equal to " + key2 + " is " + ceilingKey); } }
Output:
Contents of the TreeMap: {1=Alice, 2=Bob, 3=Charlie, 4=Dave, 5=Eve} Contents of the NavigableMap: {5=Eve, 4=Dave, 3=Charlie, 2=Bob, 1=Alice} The first key in the map is 1 The last key in the map is 5 The greatest key less than or equal to 3 is 3 The least key greater than or equal to 3 is 3
In this example, we create a TreeMap with Integer keys and String values, and insert some key-value pairs into the map using the put()
method. We then print the contents of the map using the toString()
method.
Next, we create a NavigableMap
view of the map by calling the descendingMap()
method on the map. This view represents a reverse order of the original map.
We then perform some navigation operations on the map and the navigable map view. We get the first key and last key in the map using the firstKey()
and lastKey()
methods, respectively.
We also get the greatest key less than or equal to a given key using the floorKey()
method and the least key greater than or equal to a given key using the ceilingKey()
method. We pass in the keys we want to search for as arguments. The methods return the keys that match the given criteria.
Java TreeMap Example: SortedMap
Sure! Here’s an example of how to use the SortedMap
interface, which is implemented by the TreeMap
class, to perform operations on a sorted map:
import java.util.SortedMap; import java.util.TreeMap; public class TreeMapSortedMapExample { public static void main(String[] args) { // create a TreeMap with String keys and Integer values TreeMap<String, Integer> map = new TreeMap<>(); // insert some key-value pairs into the map map.put("Bob", 2); map.put("Charlie", 3); map.put("Alice", 1); map.put("Eve", 5); map.put("Dave", 4); // print the contents of the map System.out.println("Contents of the TreeMap:"); System.out.println(map); // create a SortedMap view of the map SortedMap<String, Integer> sortedMap = map.subMap("Alice", "Dave"); // print the contents of the SortedMap System.out.println("Contents of the SortedMap:"); System.out.println(sortedMap); // get the first key in the map String firstKey = map.firstKey(); System.out.println("The first key in the map is " + firstKey); // get the last key in the map String lastKey = map.lastKey(); System.out.println("The last key in the map is " + lastKey); // remove a key-value pair from the map String keyToRemove = "Eve"; int valueToRemove = map.remove(keyToRemove); System.out.println("Removed " + keyToRemove + "=" + valueToRemove + " from the map."); // print the contents of the map after removing a key-value pair System.out.println("Contents of the TreeMap after removing " + keyToRemove + ":"); System.out.println(map); } }
Output:
Contents of the TreeMap: {Alice=1, Bob=2, Charlie=3, Dave=4, Eve=5} Contents of the SortedMap: {Alice=1, Bob=2, Charlie=3} The first key in the map is Alice The last key in the map is Eve Removed Eve=5 from the map. Contents of the TreeMap after removing Eve: {Alice=1, Bob=2, Charlie=3, Dave=4}
In this example, we create a TreeMap with String keys and Integer values, and insert some key-value pairs into the map using the put()
method. We then print the contents of the map using the toString()
method.
Next, we create a SortedMap
view of the map by calling the subMap()
method on the map. This view represents a portion of the original map, ranging from the key “Alice” (inclusive) to the key “Dave” (exclusive).
We then perform some operations on the map and the sorted map view. We get the first key and last key in the map using the firstKey()
and lastKey()
methods, respectively.
We also remove a key-value pair from the map using the remove()
method. We pass in the key we want to remove as an argument, and the method returns the value associated with that key. We print the contents of the map after removing the key-value pair using the toString()
method.
What is difference between HashMap and TreeMap?
HashMap
and TreeMap
are both implementations of the Map
interface in Java. However, they have some key differences in terms of their functionality and performance characteristics:
- Underlying data structure:
HashMap
uses a hash table to store its entries, whileTreeMap
uses a red-black tree. - Ordering:
HashMap
does not maintain any particular order of its entries, whileTreeMap
maintains the entries in sorted order based on their keys. This means thatTreeMap
is more suitable for use cases that require sorted access to the entries. - Performance:
HashMap
provides constant-timeO(1)
performance for basic operations such asget()
andput()
, assuming that the hash function is well-distributed.TreeMap
, on the other hand, providesO(log n)
performance for most operations, since it needs to perform tree traversal and balancing. - Thread-safety:
HashMap
is not thread-safe, which means that if multiple threads access the sameHashMap
concurrently, there can be race conditions and data corruption.TreeMap
is also not thread-safe by default, but it can be made thread-safe by using theCollections.synchronizedSortedMap()
method to create a synchronized view of the map.
In summary, HashMap
is generally faster and more memory-efficient than TreeMap
, but it does not provide sorted access to its entries. TreeMap
, on the other hand, is slower but provides sorted access to its entries. The choice between HashMap
and TreeMap
depends on the specific requirements of the use case.
Java TreeMap Example: Book
Here’s an example of using TreeMap
in Java to store Book
objects sorted by their titles:
import java.util.*; class Book implements Comparable<Book> { private String title; private String author; private int year; public Book(String title, String author, int year) { this.title = title; this.author = author; this.year = year; } public String getTitle() { return title; } public String getAuthor() { return author; } public int getYear() { return year; } @Override public int compareTo(Book other) { return this.title.compareTo(other.title); } @Override public String toString() { return title + " by " + author + " (" + year + ")"; } } public class BookStore { public static void main(String[] args) { // create a TreeMap to store books sorted by title Map<String, Book> bookMap = new TreeMap<>(); // add some books to the map bookMap.put("The Catcher in the Rye", new Book("The Catcher in the Rye", "J.D. Salinger", 1951)); bookMap.put("To Kill a Mockingbird", new Book("To Kill a Mockingbird", "Harper Lee", 1960)); bookMap.put("1984", new Book("1984", "George Orwell", 1949)); // print the books in the map, sorted by title for (Book book : bookMap.values()) { System.out.println(book); } } }
In this example, the Book
class implements the Comparable
interface and overrides the compareTo()
method to compare books based on their titles. The BookStore
class creates a TreeMap
to store Book
objects, and adds some books to the map using their titles as keys. Finally, the BookStore
class prints the books in the map, which are automatically sorted by title thanks to the underlying TreeMap
implementation.