Implementation of TreeMap Class in Java map

https://w‮uttual.ww‬ri.com
Implementation of TreeMap Class in Java map

The TreeMap class in Java is a implementation of the SortedMap interface that stores key-value pairs in a red-black tree. It allows you to store and retrieve elements based on a key, and provides logarithmic time performance for the basic operations (get and put). The elements in a TreeMap are sorted according to the natural ordering of the keys, or according to a Comparator provided at the time of creation of the map.

Here is an example of how to use a TreeMap in Java:

import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    // Create a TreeMap with natural ordering of the keys
    TreeMap<String, Integer> map = new TreeMap<>();

    // Add some elements to the map
    map.put("apple", 1);
    map.put("banana", 2);
    map.put("orange", 3);

    // Iterate through the map in sorted order
    for (String key : map.keySet()) {
      int value = map.get(key);
      System.out.println(key + ": " + value);
    }

    // Retrieve an element from the map
    int value = map.get("banana");
    System.out.println("The value for 'banana' is: " + value);

    // Remove an element from the map
    map.remove("apple");

    // Check if the map contains a specific key
    boolean containsKey = map.containsKey("orange");
    System.out.println("The map contains the key 'orange': " + containsKey);
  }
}

In this example, we create a TreeMap that maps strings (the keys) to integers (the values). The keys are sorted in natural order. We add some elements to the map and iterate through the map in sorted order. We also retrieve an element by its key, remove an element from the map, and check if the map contains a specific key.

Note that the TreeMap class is not synchronized, which means that it is not thread-safe. If you need a thread-safe map, you can use the Collections.synchronizedSortedMap() method to wrap a TreeMap in a synchronized map.

Created Time:2017-11-01 22:29:43  Author:lautturi