Lesson 3
Diving into Sorted Maps in Java
Diving into Sorted Maps

Hello again! This lesson's topic is Sorted Maps. Similar to other map structures, Sorted Maps store key-value pairs but in an ordered manner. Learning about Sorted Maps enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Sorted Maps using Java's TreeMap class.

Introduction: Sorted Maps in Java

In Java, we differentiate between regular maps like HashMap and Sorted Maps. Comparing HashMap to TreeMap is akin to comparing a messy bookshelf to a well-organized library — the latter maintains order. HashMap does not guarantee any order of keys, whereas TreeMap sorts the keys in natural order (if they implement the Comparable interface) or according to a specified comparator.

The TreeMap class is part of the Java Collections Framework and provides a Red-Black tree-based implementation of the NavigableMap interface. This ensures that the map is always sorted according to the natural ordering of its keys or by a custom comparator.

Discovering TreeMap

To create a TreeMap object, you can either use the default constructor or initialize it with a map. The keys used in a TreeMap must be immutable and comparable. For instance:

Java
1import java.util.TreeMap; 2 3public class TreeMapExample { 4 public static void main(String[] args) { 5 // TreeMap with fruits as keys and corresponding counts as values 6 TreeMap<String, Integer> treeMap = new TreeMap<>(); 7 treeMap.put("banana", 3); 8 treeMap.put("apple", 4); 9 treeMap.put("pear", 1); 10 treeMap.put("orange", 2); 11 12 // Print the TreeMap 13 System.out.println(treeMap); 14 } 15}

The output will be:

1{apple=4, banana=3, orange=2, pear=1}

In this example, the keys are sorted in alphabetical order. This means that "apple" comes first because 'a' is earlier in the alphabet than 'b' from "banana", 'o' from "orange", and 'p' from "pear". Conversely, "pear" is the greatest key because 'p' has a higher ASCII value than 'a', 'b', and 'o'.

Traversing TreeMap Methods

A TreeMap object boasts several useful methods. Here are some crucial ones:

  • treeMap.ceilingKey(key): This returns the least key greater than or equal to the specified key, or null if there is no such key.
  • treeMap.floorKey(key): This returns the greatest key less than or equal to the specified key, or null if there is no such key.
  • treeMap.remove(key): This removes the entry for the specified key if it is present and returns its associated value.
  • treeMap.get(key): This returns the value to which the specified key is mapped, or null if the map contains no mapping for the key.
  • treeMap.lastEntry(): This returns the key-value pair corresponding to the greatest key, or null if the map is empty.

Consider the following Java code, which incorporates these methods:

Java
1import java.util.TreeMap; 2 3public class TreeMapMethods { 4 public static void main(String[] args) { 5 // Initialize TreeMap 6 TreeMap<String, Integer> treeMap = new TreeMap<>(); 7 treeMap.put("banana", 3); 8 treeMap.put("apple", 4); 9 treeMap.put("pear", 1); 10 treeMap.put("orange", 2); 11 12 // 'apple' is less than or equal to 'apple' 13 System.out.println("Ceiling key of 'apple': " + treeMap.ceilingKey("apple")); // Output: apple 14 15 // 'apple' is less than or equal to 'apple' 16 System.out.println("Floor key of 'apple': " + treeMap.floorKey("apple")); // Output: apple 17 18 // Remove 'apple' and print the removed value 19 Integer removedValue = treeMap.remove("apple"); 20 System.out.println("Removed value: " + removedValue); // Output: 4 21 22 // Attempt to fetch a nonexisting key 23 Integer value = treeMap.get("apple"); 24 if (value == null) { 25 System.out.println("Value: Not found"); // Output: Value: Not found 26 } 27 28 // Get the last key-value pair 29 System.out.println("Last entry: " + treeMap.lastEntry()); // Output: pear=1 30 } 31}
Lesson Summary

Congratulations! You have successfully delved into Sorted Maps. This exploration included understanding the TreeMap class, creating TreeMap instances, and navigating TreeMap's valuable methods. Next, you can look forward to hands-on exercises to fortify your understanding and expand your skill set. Keep practicing!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.