TreeMap в Java

Опубликовано: 4 Февраля, 2022

TreeMap в Java используется для реализации интерфейса Map и NavigableMap вместе с классом AbstractMap. Карта сортируется в соответствии с естественным порядком ее ключей или компаратором, предоставляемым во время создания карты, в зависимости от того, какой конструктор используется. Это оказывается эффективным способом сортировки и хранения пар ключ-значение. Порядок хранения, поддерживаемый древовидной картой, должен соответствовать равенству, как и любая другая отсортированная карта, независимо от явных компараторов. Реализация древовидной карты не синхронизирована в том смысле, что если к карте обращаются одновременно несколько потоков и хотя бы один из потоков структурно модифицирует карту, она должна быть синхронизирована извне.

Example: The following implementation demonstrates how to create, insert, and traverse through the TreeMap.

// Java code to show creation, insertion,
// searching, and traversal in a TreeMap
  
import java.util.*;
import java.util.concurrent.*;
  
public class TreeMapImplementation {
  
    // Declaring a TreeMap
    static TreeMap<Integer, String> tree_map;
  
    // Function to create TreeMap
    static void create()
    {
        // Creating an empty TreeMap
        tree_map
            = new TreeMap<Integer, String>();
  
        System.out.println(
            "TreeMap successfully"
            + " created");
    }
  
    // Function to Insert values in
    // the TreeMap
    static void insert()
    {
        // Mapping string values to int keys
        tree_map.put(10, "Geeks");
        tree_map.put(15, "4");
        tree_map.put(20, "Geeks");
        tree_map.put(25, "Welcomes");
        tree_map.put(30, "You");
  
        System.out.println(
            " Elements successfully"
            + " inserted in the TreeMap");
    }
  
    // Function to search a key in TreeMap
    static void search(int key)
    {
  
        // Checking for the key
        System.out.println(
            " Is key ""
            + key + "" present? "
            + tree_map.containsKey(key));
    }
  
    // Function to search a value in TreeMap
    static void search(String value)
    {
  
        // Checking for the value
        System.out.println(
            " Is value ""
            + value + "" present? "
            + tree_map.containsValue(value));
    }
  
    // Function to display the elements in TreeMap
    static void display()
    {
        // Displaying the TreeMap
        System.out.println(
            " Displaying the TreeMap:");
  
        System.out.println(
            "TreeMap: " + tree_map);
    }
  
    // Function to traverse TreeMap
    static void traverse()
    {
        System.out.println(" Traversing the TreeMap:");
        for (Map.Entry<Integer, String> e : tree_map.entrySet())
            System.out.println(e.getKey()
                               + " "
                               + e.getValue());
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating the TreeMap
        create();
  
        // Inserting values in the TreeMap
        insert();
  
        // Search key "50" in the TreeMap
        search(50);
  
        // Search value "Geeks" in the TreeMap
        search("Geeks");
  
        // Display the elements in TreeMap
        display();
  
        // Traverse the TreeMap
        traverse();
    }
}
Output:
TreeMap successfully created
Elements successfully inserted in the TreeMap
Is key "50" present? false
Is value "Geeks" present? true
Displaying the TreeMap:
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Traversing the TreeMap:
10 Geeks
15 4
20 Geeks
25 Welcomes
30 You

Performing Various Operations on TreeMap

После введения Generics в Java 1.5 стало возможным ограничить тип объекта, который может храниться в TreeMap. Теперь давайте посмотрим, как выполнять несколько часто используемых операций с TreeMap.

1. Adding Elements: In order to add an element to the TreeMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in the ascending order.

// Java program to demonstrate
// the working of TreeMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Default Initialization of a
        // TreeMap
        TreeMap tm1 = new TreeMap();
  
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm2
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm1.put(3, "Geeks");
        tm1.put(2, "For");
        tm1.put(1, "Geeks");
  
        tm2.put(new Integer(3), "Geeks");
        tm2.put(new Integer(2), "For");
        tm2.put(new Integer(1), "Geeks");
  
        System.out.println(tm1);
        System.out.println(tm2);
    }
}
Output:
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the treemap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

// Java program to demonstrate
// the working of TreeMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
  
        System.out.println(tm);
  
        tm.put(2, "For");
  
        System.out.println(tm);
    }
}
Output:
{1=Geeks, 2=Geeks, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

3. Removing Element: In order to remove an element from the TreeMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this treemap if it is present in the map.

// Java program to demonstrate
// the working of TreeMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
        tm.put(4, "For");
  
        System.out.println(tm);
  
        tm.remove(4);
  
        System.out.println(tm);
    }
}
Output:
{1=Geeks, 2=Geeks, 3=Geeks, 4=For}
{1=Geeks, 2=Geeks, 3=Geeks}

4. Iterating through the TreeMap: There are multiple ways to iterate through the Map. The most famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method.

// Java program to demonstrate
// the working of TreeMap
  
import java.util.*;
class GFG {
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "For");
        tm.put(1, "Geeks");
  
        for (Map.Entry mapElement : tm.entrySet()) {
            int key
                = (int)mapElement.getKey();
  
            // Finding the value
            String value
                = (String)mapElement.getValue();
  
            System.out.println(key + " : "
                               + value);
        }
    }
}
Output:

1 : Geeks
2 : For
3 : Geeks