Java Code Example: advanced TreeMap example

import java.util.Comparator;
import java.util.TreeMap;

public class AdvancedTreeMapExample {
    public static void main(String[] args) {
        // create a TreeMap with a custom comparator
        TreeMap<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());

        // put some key-value pairs in the map
        treeMap.put("Alice", 25);
        treeMap.put("Bob", 30);
        treeMap.put("Charlie", 35);
        treeMap.put("David", 40);

        // print the TreeMap
        System.out.println("TreeMap: " + treeMap);

        // get the key-value pair with the greatest key less than or equal to "Charlie"
        String lowerKey = treeMap.lowerKey("Charlie");
        int lowerValue = treeMap.get(lowerKey);
        System.out.println("Key-value pair with greatest key less than or equal to Charlie: " + lowerKey + "=" + lowerValue);

        // get the key-value pair with the least key greater than or equal to "Charlie"
        String ceilingKey = treeMap.ceilingKey("Charlie");
        int ceilingValue = treeMap.get(ceilingKey);
        System.out.println("Key-value pair with least key greater than or equal to Charlie: " + ceilingKey + "=" + ceilingValue);
    }
}

This code creates a TreeMap called treeMap, which maps String keys to Integer values. We specify a custom comparator using the Comparator.reverseOrder() method, which sorts the keys in reverse order.

We then add some key-value pairs to the map using the put() method.

We retrieve the key-value pair with the greatest key less than or equal to "Charlie" using the lowerKey() and get() methods, and print it.

We then retrieve the key-value pair with the least key greater than or equal to "Charlie" using the ceilingKey() and get() methods, and print it.

The output of this code will be:

TreeMap: {David=40, Charlie=35, Bob=30, Alice=25}
Key-value pair with greatest key less than or equal to Charlie: Bob=30
Key-value pair with least key greater than or equal to Charlie: Charlie=35

This example demonstrates some of the more advanced features of TreeMap, including the ability to specify a custom comparator and retrieve key-value pairs based on their position in the sorted order of the keys.