Storing Data in a Java TreeMap
Creating a Java TreeMap
To create a TreeMap
, you can use the following syntax:
TreeMap<K, V> treeMap = new TreeMap<>();
Here, K
represents the type of the keys, and V
represents the type of the values stored in the TreeMap
.
Adding Elements to a Java TreeMap
You can add elements to a TreeMap
using the put()
method:
treeMap.put(key, value);
If the key already exists in the TreeMap
, the associated value will be overwritten.
Specifying a Custom Comparator
By default, the TreeMap
uses the natural ordering of the keys (e.g., ascending order for numbers, alphabetical order for strings). However, you can provide a custom Comparator
to sort the keys in a different order:
Comparator<K> comparator = (k1, k2) -> k2.compareTo(k1); // Descending order
TreeMap<K, V> treeMap = new TreeMap<>(comparator);
Example: Storing Student Records in a Java TreeMap
Let's consider an example where we want to store student records in a TreeMap
, using the student's ID as the key and the student's name as the value.
TreeMap<Integer, String> studentRecords = new TreeMap<>();
// Add student records
studentRecords.put(101, "John Doe");
studentRecords.put(205, "Jane Smith");
studentRecords.put(150, "Michael Johnson");
studentRecords.put(87, "Emily Williams");
// Print the student records
for (Map.Entry<Integer, String> entry : studentRecords.entrySet()) {
System.out.println("Student ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
Output:
Student ID: 87, Name: Emily Williams
Student ID: 101, Name: John Doe
Student ID: 150, Name: Michael Johnson
Student ID: 205, Name: Jane Smith
In this example, the TreeMap
stores the student records, with the student ID as the key and the student name as the value. The records are automatically sorted by the student ID in ascending order.