TreeMap en Java
Outre la classe AbstractMap, TreeMap de Java implémente discrètement l'interface Map et NavigableMap. Selon le constructeur utilisé, la carte est triée soit par l'ordre naturel de ses clés, soit par un comparateur spécifié au moment de la création de la carte.
Il s'agit d'une méthode efficace de tri et de stockage des paires clé-valeur. Quels que soient les comparateurs spécifiés, l'ordre de stockage du treemap doit être cohérent avec des égaux, comme n'importe quelle autre carte triée. L'implémentation d'un treemap est présentée comme non synchronisée car une map doit être synchronisée en externe si elle est utilisée par plusieurs threads simultanément, et qu'au moins un des threads modifie fondamentalement la map.
Déclaration de classe pour TreeMap
Regardons la déclaration de classe java.util.TreeMap.
public class TreeMap<Key,Value> extends AbstractMap<Key,Value> implements NavigableMap<Key,Value>, Cloneable, Serializable
Paramètres de classe pour TreeMap
Regardons les paramètres de la classe java.util.TreeMap.
- Le type de touches de cette carte est désigné par la lettre K.
- Le type de valeur mappée est V.
Caractéristiques de l'arborescence
Voici quelques-unes des fonctionnalités clés du treemap :
- Le Java Collections Framework inclut cette classe.
- La classe étend AbstractMap et implémente des interfaces Map telles que NavigableMap et SortedMap.
- Étant donné que TreeMap (contrairement à Map) n'accepte pas les clés nulles, une exception NullPointerException est déclenchée.
- D'autre part, plusieurs valeurs nulles peuvent être associées à des clés distinctes.
- Les paires d'entrées données par les méthodes et les vues de cette classe sont des instantanés des mappages pris lors de leur création.
- La méthode Entry.setValue n'est pas prise en charge.
Il est maintenant temps de parler de Synchronized TreeMap. L'implémentation TreeMap n'est pas synchronisée. Cela signifie que si plusieurs threads visitent simultanément un ensemble d'arbres et qu'au moins l'un d'entre eux le met à jour, l'ensemble doit être synchronisé en externe. La méthode Collections.synchronizedSortedMap est couramment utilisée pour accomplir cela. Cela doit être fait au moment de la création pour éviter un accès non synchronisé involontaire à l'ensemble. Ceci peut être accompli en :
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));
Vous vous demandez probablement comment le TreeMap fonctionne à l'intérieur.
Les méthodes d'un TreeMap renvoient un itérateur qui est à sécurité intégrée pour obtenir le jeu de clés et les valeurs. ConcurrentModificationException sera levée pour toute modification simultanée. La structure de données d'un TreeMap est un arbre rouge-noir. Chaque nœud de l'arborescence possède les propriétés suivantes :
3 variables (key=Key, value=Value, boolean color=Color) 3 references (Entry lft = Left, Entry rgt = Right, Entry parent = Parent)
Constructeurs TreeMap
Lors de la création d'un TreeMap, nous devons d'abord créer un objet TreeMap. La classe TreeMap contient plusieurs constructeurs qui permettent de créer le TreeMap. Les constructeurs disponibles dans cette classe sont les suivants :
- Carte arborescente()
- TreeMap (comparateur)
- Carte arborescente(Carte M)
- TreeMap(SortedMap sm)
Passons en revue chacun individuellement avant d'implémenter chaque constructeur :
Le premier constructeur :TreeMap
Ce constructeur crée un treemap vide qui sera trié selon l'ordre naturel de ses clés. Exemple :
// Program for demonstrating the TreeMap using the Default Constructor // Importing required classes import java.util.*; import java.util.concurrent.*; // TreeMapImplementation is the Main class public class Codeunderscored { // Method one showing the TreeMap constructor static void CodeFirstConstructor() { // Creation of an empty TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Mapping string values to int keys // using put() method treeMap.put(1, "Code"); treeMap.put(18, "Underscored"); treeMap.put(16, "Coding"); treeMap.put(34, "Java"); treeMap.put(12, "Extravaganza"); // how to print the TreeMap elements System.out.println(" The TreeMap is as follows: " + treeMap); } // Method Two: The primary driver method public static void main(String[] args) { System.out.println("TreeMap using the "+ "TreeMap() constructor:\n"); // Calling constructor CodeFirstConstructor(); } }
Le deuxième constructeur :TreeMap(Comparator comp)
Ce constructeur est responsable de la création d'un objet TreeMap vide avec des nœuds qui nécessitent une spécification d'ordre de tri externe.
// Program for demonstrating TreeMap using the Comparator Constructor //First, import the needed classes import java.util.*; import java.util.concurrent.*; // Class 1: This is the helper class for CodeStudent class CodeStudent { // CodeStudent's attributes int c_rollno; String c_name, c_address; // Constructor public CodeStudent(int c_rollno, String c_name, String c_address) { // This keyword refers to current object itself this.c_rollno = c_rollno; this.c_name = c_name; this.c_address = c_address; } // class's method for printing CodeStudent details public String toString() { return this.c_rollno + " " + this.c_name + " " + this.c_address; } } // Class Two: This is the helper class for implementing a Comparator class CodeSortByRoll implements Comparator<CodeStudent> { // responsible for sorting the student's roll number in ascending order public int compare(CodeStudent aVar, CodeStudent bVar) { return aVar.c_rollno - bVar.c_rollno; } } // Class Three: This is the Main class public class Code { // here, we call the constructor inside main() static void CodeSecondConstructor() { // Creation of an empty TreeMap TreeMap<CodeStudent, Integer> treeMap = new TreeMap<CodeStudent, Integer>( new CodeSortByRoll()); // Mapping string values to int keys treeMap.put(new CodeStudent(1, "Joy", "Manchester"), 2); treeMap.put(new CodeStudent(2, "Green", "LA"), 3); treeMap.put(new CodeStudent(3, "Tyson", "New York"), 1); // Print the TreeMap elements System.out.println(" The TreeMap is: " + treeMap); } // The driver;s main method public static void main(String[] args) { System.out.println("The TreeMap using " + "TreeMap(Comparator)" + " constructor:\n"); CodeSecondConstructor(); } }
Le troisième constructeur :TreeMap (Map M)
Ce constructeur est utilisé pour remplir un TreeMap avec des entrées d'une carte spécifiée "M", qui seront triées selon l'ordre naturel des clés.
Exemple
// Program for illustrating the TreeMap through the Default Constructor //First, Import the required classes import java.util.*; import java.util.concurrent.*; // This is the Main class public class CodeTreeMapImplementation { // Method 1: illustrates the constructor<Map> static void CodeThirdConstructor() { // Creation of an empty HashMap Map<Integer, String> hashMap = new HashMap<Integer, String>(); // using the put() method to Map string values to respective int keys hashMap.put(8, "Code"); hashMap.put(3, "Underscored"); hashMap.put(7, "Coding"); hashMap.put(11, "Challenge"); hashMap.put(5, "2022"); // Creation of the TreeMap by using the Map TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(hashMap); // Printing the TreeMap elements System.out.println("The TreeMap is: " + treeMap); } // Method 2: This is the driver's main method public static void main(String[] args) { System.out.println(" The TreeMap using the " + "TreeMap(Map)" + " constructor:\n"); CodeThirdConstructor(); } }
Le quatrième constructeur :TreeMap(SortedMap sm)
Ce constructeur remplit un TreeMap avec les éléments de la carte triée spécifiée, stockés dans le même ordre que la carte triée.
// Program for illustrating the TreeMap throughout the SortedMap Constructor // First, Import the needed classes import java.util.*; import java.util.concurrent.*; // TreeMapImplementation- Main class public class Codeunderscored { // Method for showing TreeMap(SortedMap) constructor static void CodeFourthConstructor() { // Creating a SortedMap SortedMap<Integer, String> sortedMap = new ConcurrentSkipListMap<Integer, String>(); // using the put() method for mapping values of type string to int keys sortedMap.put(8, "Code"); sortedMap.put(3, "Underscored"); sortedMap.put(7, "Coding"); sortedMap.put(11, "Challenge"); sortedMap.put(5, "2022"); // Creation of the TreeMap using the SortedMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(sortedMap); // Printing of the elements of the TreeMap System.out.println("The TreeMap is: " + treeMap); } // Method 2: The driver's Main method public static void main(String[] args) { System.out.println("This is the TreeMap using the: " + "TreeMap(SortedMap)" + " constructor:\n"); CodeFourthConstructor(); } }
Les méthodes de la classe TreeMap
effacer()
La méthode efface la carte et supprime tous les mappages du TreeMap.
cloner()
Une copie superficielle de ce TreeMap est renvoyée par cette méthode.
containsKey (clé d'objet)
Si cette carte a un mappage pour la clé fournie, elle renvoie true.
containsValue (valeur de l'objet)
Si cette carte est responsable du mappage d'une ou plusieurs clés à la valeur fournie, elle renvoie true.
entrySet()
Cette méthode est chargée de renvoyer une vue définie des mappages de cette carte.
premièreClé()
Renvoie la première clé (la plus basse) de la carte triée actuelle.
obtenir (clé d'objet)
Renvoie la valeur à laquelle cette carte mappe la clé fournie.
headMap(Object key_value)
La méthode renvoie une vue de la section de la carte qui est strictement inférieure au paramètre key_value.
keySet()
La méthode renvoie une représentation Set des clés du treemap.
dernièreClé()
Renvoie la dernière clé (la plus élevée) de la carte triée actuelle.
mettre (clé d'objet, valeur d'objet)
Un mappage est inséré dans une carte de cette manière.
putAll(Map map)
Tous les mappages de la carte spécifiée sont copiés sur cette carte.
supprimer (clé d'objet)
Si ce TreeMap a un mappage pour cette clé, il est supprimé.
taille()
Le nombre de mappages clé-valeur dans cette carte est renvoyé.
subMap((K startKey, K endKey)
La méthode renvoie la partie de la carte avec des clés allant de startKey à endKey, inclusives et exclusives.
valeurs()
Cette méthode est chargée de renvoyer une vue de collection des valeurs de cette carte.
Les programmes suivants vous montreront comment créer, insérer et parcourir l'implémentation TreeMap.
Exemple :Programme pour illustrer les opérations dans TreeMap
// TreeMap operations include: Creation, insertion, searching, and traversal //First, importing the necessary classes import java.util.*; import java.util.concurrent.*; // This is the class's main implementation of the TreeMap public class Codeunderscored { // Declaration of a TreeMap static TreeMap<Integer, String> treeMap; // Method One: Creation of a TreeMap static void CodeCreate() { // Creating an empty TreeMap treeMap = new TreeMap<Integer, String>(); // Display message only System.out.println("TreeMap has been created successfully"); } // Method Two: Inserting values in the TreeMap static void CodeInsert() { // using put() method to map values of string type to int keys treeMap.put(8, "Code"); treeMap.put(3, "Underscored"); treeMap.put(7, "Coding"); treeMap.put(11, "Challenge"); treeMap.put(5, "2022"); // Display message only System.out.println("\nPrinting the Elements successfully" + " after initial insert to the TreeMap"); } // Method three: / searching for a key in the givenTreeMap static void CodeSearch(int key) { // looking for the key System.out.println("\nThis is the key \"" + key + "\" present? " + treeMap.containsKey(key)); } // Method Four: searching for value in the provided TreeMap static void CodeSearch(String value) { // Checking for the value System.out.println("\nThis is the value \"" + value + "\" present? " + treeMap.containsValue(value)); } // Method Five: displaying elements in the provided TreeMap static void CodeDisplay() { // showing the TreeMap System.out.println("\nShowing the TreeMap:"); System.out.println("The TreeMap is: " + trerMap); } // Method Six: traversing through the TreeMap static void CodeTraverse() { // showing message explicitly System.out.println("\nTreeMap Traversal:"); for (Map.Entry<Integer, String> eVar : treeMap.entrySet()) System.out.println(eVar.getKey() + " " + eVar.getValue()); } // Method 7: This is the driver's Main method public static void main(String[] args) { // Calling the above-defined methods inside the main() // Creation of a TreeMap CodeCreate(); // Insertion of values in the TreeMap CodeInsert(); // searching for key "2022" in the provided TreeMap CodeSearch(2022); // Searching for the value "Coding" in the TreeMap CodeSearch("Coding"); // Displaying the TreeMap's elements CodeDisplay(); // TreeMap Traversal CodeTraverse(); } }
Utiliser TreeMap pour effectuer diverses opérations
Il est désormais possible de limiter le type d'objet pouvant être mis dans le TreeMap grâce à l'avènement des Generics en Java 1.5. Voyons comment utiliser le TreeMap pour accomplir quelques opérations courantes.
Opération 1 :Ajouter des éléments
La méthode put() peut ajouter un élément au TreeMap. Dans le TreeMap, cependant, l'ordre d'insertion n'est pas conservé. En interne, les clés sont comparées et triées par ordre croissant pour chaque élément. Les méthodes courantes d'ajout d'éléments incluent :
- put() -Place le mappage clé/valeur fourni (entrée) dans la carte.
- PutAll() - Met toutes les entrées d'une carte spécifiée dans cette carte.
- PutIfAbsent() – Si la clé fournie n'est pas présente dans la carte, putIfAbsent() ajoute le mappage clé/valeur spécifié à la carte.
// Program for demonstrating the addition of Elements in TreeMap through the put() Method // First, import the necessary classes import java.util.*; // This is the Main class class Codeunderscored { // This is the driver's Main method public static void main(String args[]) { // Initialization of a given TreeMap by default TreeMap treeMap = new TreeMap(); // using the put() method to Insert elements in TreeMap treeMap.put(3, "Code"); treeMap.put(2, "Underscored"); treeMap.put(1, "Coding"); // Initializing a TreeMap through use of Generics TreeMap<Integer, String> treeMapTwo = new TreeMap<Integer, String>(); // using the method, "put()" to insert elements in the TreeMap given treeMapTwo.put(new Integer(3), "Code"); treeMapTwo.put(new Integer(2), "Underscored"); treeMapTwo.put(new Integer(1), "Coding"); // Printing the elements of both TreeMaps // Tree Map One System.out.println(treeMap); // Tree Map Two System.out.println(treeMapTwo); } } import java.util.TreeMap; class CodeAdd { public static void main(String[] args) { //Making an even-numbered TreeMap TreeMap<String, Integer> treeMap = new TreeMap<>(); // Making use of the put() method treeMap.put("Eight", 8); treeMap.put("Twelve", 12); // making use of the putIfAbsent() ethod treeMap.putIfAbsent("Six", 6); System.out.println("TreeMap of even numbers: " + treeMap); //Making a number TreeMap TreeMap<String, Integer> numbers = new TreeMap<>(); treeMap.put("One", 1); // Using the putAll() method numbers.putAll(treeMap); System.out.println("TreeMap of of the given numbers: " + treeMap); } }
Opération 2 :Accès à l'élément TreeMap
Utilisation de values(), keySet() et entrySet()
- entrySet() – renvoie une collection de tous les mappages clé/valeur (entrée) pour une clé de treemap.
- keySet() - renvoie une collection de toutes les clés dans un treemap.
- values() - fournit une collection de cartes d'arbres.
import java.util.TreeMap; class CodeElementAccess { public static void main(String[] args) { TreeMap<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Eleven", 11); treeMap.put("Twelve", 12); treeMap.put("Thirteen", 13); System.out.println("The TreeMap is: " + treeMap); // utilizing the entrySet() method System.out.println("The Key/Value mappings include: " + treeMap.entrySet()); // utilizing the keySet() method System.out.println("The Keys include: " + treeMap.keySet()); // utilizing the values() method System.out.println("The Values Include: " + treeMap.values()); } }
Utiliser les fonctions get() et getOrDefault()
- get() – Renvoie la valeur qui correspond à la clé fournie. Si la clé ne peut pas être récupérée, null est renvoyé.
- getOrDefault() – Obtient la valeur par défaut pour la clé fournie. Si la clé ne peut pas être découverte, la valeur par défaut est renvoyée.
Par exemple,
import java.util.TreeMap; class CodeElementAccessTwo { public static void main(String[] args) { TreeMap<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Eleven", 11); treeMap.put("Twelve", 12); treeMap.put("Thirteen", 13); System.out.println("The TreeMap is: " + treeMap); // Using get() int valOne = numbers.get("Twelve"); System.out.println("Using get(): " + valOne); // Using getOrDefault() int valTwo = numbers.getOrDefault("Ten", 10); System.out.println("Using getOrDefault(): " + valTwo); } }
La méthode getOrDefault() ne parvient pas à localiser la clé Ten dans ce cas. En conséquence, le nombre par défaut 10 est renvoyé.
Opération 3 :Changer d'éléments
Si nous voulons mettre à jour un élément après son ajout, nous pouvons le faire en utilisant la méthode put () pour l'ajouter à nouveau. Étant donné que les clés sont utilisées pour indexer les éléments dans le treemap, la valeur de la clé peut être modifiée en ajoutant simplement la valeur mise à jour pour la clé que nous voulons modifier.
// program for Illustrating how to Updat TreeMap elements using the put() Method // First, import the needed classes import java.util.*; // This is the Main class class CodeUnderscored { // Main driver method public static void main(String args[]) { // use Generics in the initialization of a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Inserting the elements in Map // using put() method treeMap.put(3, "Code"); treeMap.put(2, "Code"); treeMap.put(1, "Code"); // Printing of all the current elements in the map System.out.println(treeMap); // Insertion of the element at the specified place corresponding to the key given treeMap.put(2, "Underscored"); // Now, print the Maps' updated elements System.out.println(treeMap); } }
Opération quatre :suppression d'éléments
La méthode remove() peut supprimer un élément du TreeMap. Si la valeur de la clé est présente dans le mappage, cette méthode supprime le mappage de la clé du treemap.
Exemple
// Program for Illustrating Elements' Removal in the TreeMap using the method remove() // First, importing the necessary classes import java.util.*; // This is the Main class class CodeUnderscored { // This is the driver's Main method public static void main(String args[]) { // Employ Generics to initialize a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Inserting the elements // using put() method treeMap.put(3, "Code"); treeMap.put(2, "Underscored"); treeMap.put(1, "Coding"); treeMap.put(4, "2022"); // All the Map elements require printing System.out.println(treeMap); // Removal of the element that corresponds to the provided key treeMap.remove(2); // The updated TreeMap can now be Printed System.out.println(treeMap); } }
Opération 5 :Itérer dans le TreeMap
Il existe plusieurs méthodes pour parcourir la carte. La méthode la plus connue consiste à utiliser une boucle for-each pour obtenir les clés. La méthode getValue() est désignée pour déterminer la valeur de la clé.
Exemple
// Program for Illustrating Iteration over the TreeMap // First, import the necessary classes import java.util.*; // This is the Main class class CodeUnderscored { // This is the driver's Main method public static void main(String args[]) { // Employ Generics to initialize a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // use the method, put(), to insert the element's treeMap.put(3, "Code"); treeMap.put(2, "Underscored"); treeMap.put(1, "Coding"); // Use the entrySet() Method in a for-each loop traversal of the Map for (Map.Entry mapElement : treeMap.entrySet()) { int keyVar = (int)mapElement.getKey(); // locating the value String valueVar = (String)mapElement.getValue(); // Printing the keyVar and valueVar System.out.println(keyVar + " : " + valueVar); } } }
Comparateur de TreeMaps
Les éléments de la carte arborescente sont organisés de manière organique dans toutes les instances ci-dessus (par ordre croissant). On peut cependant changer la séquence des touches. Nous devrons créer notre classe de comparaison en fonction de la manière dont les clés d'un treemap sont disposées. Par exemple,
import java.util.TreeMap; import java.util.Comparator; class CodeCompartor { public static void main(String[] args) { // Using a custom comparator to create a treemap TreeMap<String, Integer> treeMap = new TreeMap<>(new CustomComparator()); treeMap.put("Eleventh", 11); treeMap.put("Twelveth",12); treeMap.put("Thirteenth", 13); treeMap.put("Fourteenth", 14); System.out.println("TreeMap: " + treeMap); } // Constructing a comparator class public static class CodeComparator implements Comparator<String> { @Override public int compare(String numberOne, String numberTwo) { int valVar = numberOne.compareTo(numberTwo); // reversing the order of elements if ( valVar > 0) { return -1; } else if ( valVar < 0) { return 1; } else { return 0; } } } }
Exemple :Java TreeMap
import java.util.*; class CodeTreeMap1{ public static void main(String args[]){ TreeMap<Integer,String> treeMap=new TreeMap<Integer,String>(); treeMap.put(02,"Green"); treeMap.put(05,"Joy"); treeMap.put(07,"Bright"); treeMap.put(09,"Lucy"); for(Map.Entry m:treeMap.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
Exemple :Java TreeMap remove()
import java.util.*; public class CodeTreeMap { public static void main(String args[]) { TreeMap<Integer,String> treeMap=new TreeMap<Integer,String>(); treeMap.put(02,"Green"); treeMap.put(05,"Joy"); treeMap.put(07,"Bright"); treeMap.put(09,"Lucy"); System.out.println(" Results prior to invoking the remove() method"); for(Map.Entry m:treeMap.entrySet()) { System.out.println(m.getKey()+" "+m.getValue()); } map.remove(02); System.out.println("Results proceeding the invoking of the remove() method"); for(Map.Entry m:treeMap.entrySet()) { System.out.println(m.getKey()+" "+m.getValue()); } } }
Exemple :Java TreeMap NavigableMap
import java.util.*; class CodeTreeMap{ public static void main(String args[]){ NavigableMap<Integer,String> treeMap=new TreeMap<Integer,String>(); treeMap.put(02,"Green"); treeMap.put(05,"Joy"); treeMap.put(07,"Bright"); treeMap.put(09,"Lucy"); //Keeps the descending order System.out.println("descendingMap: "+treeMap.descendingMap()); //Key-value pairs having keys that are less than or equal to the specified key are returned. System.out.println("headMap: "+treeMap.headMap(02,true)); //Returns key-value pairs with keys equal to or greater than the supplied key. System.out.println("tailMap: "+treeMap.tailMap(02,true)); //responsible for returning the count of key-value pairs between the provided keys. System.out.println("subMap: "+treeMap.subMap(09, false, 02, true)); } }
Exemple :Java TreeMap SortedMap
import java.util.*; class CodeTreeMap{ public static void main(String args[]){ SortedMap<Integer,String> treeMap=new TreeMap<Integer,String>(); treeMap.put(02,"Green"); treeMap.put(05,"Joy"); treeMap.put(07,"Bright"); treeMap.put(09,"Lucy"); //Key-value pairs with keys smaller than the specified key are returned. System.out.println("The headMap is: "+map.headMap(02)); //Returns key-value pairs with keys equal to or greater than the supplied key. System.out.println("The tailMap is: "+map.tailMap(02)); //responsible for returning the count of key-value pairs between the provided keys. System.out.println("The subMap is: "+map.subMap(09, 02)); } }
Exemple :ordinateur portable Java TreeMap
import java.util.*; class Laptop { int id; String name,author,publisher; int quantity; public Laptop(int id, String name, String model, String manufacturer, int quantity) { this.id = id; this.name = name; this.model = model; this.manufacturer = manufacturer; this.quantity = quantity; } } public class CodeMap { public static void main(String[] args) { //Creating map of Laptops Map<Integer,Laptop> treeMap=new TreeMap<Integer,Laptop>(); //Creating Laptops Laptop laptopOne=new Laptop(1,"Lenovo Yoga","LN90THY","Lenovo",20); Laptop laptopTwo=new Laptop(2,"HP Probook","P8976T","HP",5); Laptop laptopThree=new Laptop(3,"Toshiba Slim","T999T","Toshiba",2); //Adding Laptops to map treeMap.put(2,laptopTwo); treeMap.put(1,laptopOne); treeMap.put(3,laptopThree); //Traversing map for(Map.Entry<Integer, Laptop> entry:treeMap.entrySet()){ int key=entry.getKey(); Laptop bVar=entry.getValue(); System.out.println(key+" Details:"); System.out.println(bVar .id+" "+bVar.name+" "+bVar.model+" "+bVar.manufacturer+" "+b.quantity); } } }
Conclusion
À l'aide d'exemples, nous avons découvert la classe Java TreeMap et ses actions dans cet article. La structure de données arborescente est implémentée par la classe TreeMap du framework de collections Java. De plus, l'interface NavigableMap est implémentée.
La classe TreeMap utilise un arbre pour implémenter l'interface Map. Un TreeMap est un moyen efficace de stocker des paires clé/valeur dans un ordre trié et de les récupérer rapidement. Il convient de noter que, contrairement à une carte de hachage, une arborescence garantit que les éléments sont classés dans l'ordre croissant des clés. De plus, la classe Java TreeMap implémente un modèle d'arbre rouge-noir. Il facilite le stockage rapide des paires clé-valeur dans un ordre trié.