TreeMap en Java

TreeMap en Java se utiliza para implementar la interfaz Map y NavigableMap junto con la clase AbstractMap. El mapa se ordena según el orden natural de sus claves, o mediante un comparador proporcionado en el momento de la creación del mapa, según el constructor que se utilice. Esto demuestra ser una forma eficiente de ordenar y almacenar los pares clave-valor. El orden de almacenamiento mantenido por el mapa de árbol debe ser consistente con iguales al igual que cualquier otro mapa ordenado, independientemente de los comparadores explícitos. La implementación del mapa de árbol no está sincronizada en el sentido de que si varios subprocesos acceden a un mapa al mismo tiempo y al menos uno de los subprocesos modifica el mapa estructuralmente, debe sincronizarse externamente. 

Java

// Java Program to Demonstrate TreeMap
// using the Default Constructor
  
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
  
// Main class
// TreeMapImplementation
public class GFG {
  
    // Method 1
    // To show TreeMap constructor
    static void Example1stConstructor()
    {
        // Creating an empty TreeMap
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Mapping string values to int keys
        // using put() method
        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");
  
        // Printing the elements of TreeMap
        System.out.println("TreeMap: " + tree_map);
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        System.out.println("TreeMap using "
                           + "TreeMap() constructor:\n");
  
        // Calling constructor
        Example1stConstructor();
    }
}

Java

// Java Program to Demonstrate TreeMap
// using Comparator Constructor
  
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
  
// Class 1
// Helper class representing Student
class Student {
  
    // Attributes of a student
    int rollno;
    String name, address;
  
    // Constructor
    public Student(int rollno, String name, String address)
    {
  
        // This keyword refers to current object itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
  
    // Method of this class
    // To print student details
    public String toString()
    {
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
  
// Class 2
// Helper class - Comparator implementation
class Sortbyroll implements Comparator<Student> {
  
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
  
// Class 3
// Main class
public class GFG {
  
    // Calling constructor inside main()
    static void Example2ndConstructor()
    {
        // Creating an empty TreeMap
        TreeMap<Student, Integer> tree_map
            = new TreeMap<Student, Integer>(
                new Sortbyroll());
  
        // Mapping string values to int keys
        tree_map.put(new Student(111, "bbbb", "london"), 2);
        tree_map.put(new Student(131, "aaaa", "nyc"), 3);
        tree_map.put(new Student(121, "cccc", "jaipur"), 1);
  
        // Printing the elements of TreeMap
        System.out.println("TreeMap: " + tree_map);
    }
  
    // Main driver method
    public static void main(String[] args)
    {
  
        System.out.println("TreeMap using "
                           + "TreeMap(Comparator)"
                           + " constructor:\n");
        Example2ndConstructor();
    }
}

Java

// Java Program to Demonstrate TreeMap
// using the Default Constructor
  
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
  
// Main class
public class TreeMapImplementation {
  
    // Method 1
    // To illustrate constructor<Map>
    static void Example3rdConstructor()
    {
        // Creating an empty HashMap
        Map<Integer, String> hash_map
            = new HashMap<Integer, String>();
  
        // Mapping string values to int keys
        // using put() method
        hash_map.put(10, "Geeks");
        hash_map.put(15, "4");
        hash_map.put(20, "Geeks");
        hash_map.put(25, "Welcomes");
        hash_map.put(30, "You");
  
        // Creating the TreeMap using the Map
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>(hash_map);
  
        // Printing the elements of TreeMap
        System.out.println("TreeMap: " + tree_map);
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
  
        System.out.println("TreeMap using "
                           + "TreeMap(Map)"
                           + " constructor:\n");
  
        Example3rdConstructor();
    }
}

Java

// Java Program to Demonstrate TreeMap
// using the SortedMap Constructor
  
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
  
// Main class
// TreeMapImplementation
public class GFG {
  
    // Method
    // To show TreeMap(SortedMap) constructor
    static void Example4thConstructor()
    {
        // Creating a SortedMap
        SortedMap<Integer, String> sorted_map
            = new ConcurrentSkipListMap<Integer, String>();
  
        // Mapping string values to int keys
        // using put() method
        sorted_map.put(10, "Geeks");
        sorted_map.put(15, "4");
        sorted_map.put(20, "Geeks");
        sorted_map.put(25, "Welcomes");
        sorted_map.put(30, "You");
  
        // Creating the TreeMap using the SortedMap
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>(sorted_map);
  
        // Printing the elements of TreeMap
        System.out.println("TreeMap: " + tree_map);
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
  
        System.out.println("TreeMap using "
                           + "TreeMap(SortedMap)"
                           + " constructor:\n");
  
        Example4thConstructor();
    }
}

Java

// Java Program to Illustrate Operations in TreeMap
// Such as Creation, insertion
// searching, and traversal
  
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
  
// Main class
// Implementation of TreeMap
public class GFG {
  
    // Declaring a TreeMap
    static TreeMap<Integer, String> tree_map;
  
    // Method 1
    // To create TreeMap
    static void create()
    {
  
        // Creating an empty TreeMap
        tree_map = new TreeMap<Integer, String>();
  
        // Display message only
        System.out.println("TreeMap successfully"
                           + " created");
    }
  
    // Method 2
    // To Insert values in the TreeMap
    static void insert()
    {
  
        // Mapping string values to int keys
        // using put() method
        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");
  
        // Display message only
        System.out.println("\nElements successfully"
                           + " inserted in the TreeMap");
    }
  
    // Method 3
    // To search a key in TreeMap
    static void search(int key)
    {
  
        // Checking for the key
        System.out.println("\nIs key \"" + key
                           + "\" present? "
                           + tree_map.containsKey(key));
    }
  
    // Method 4
    // To search a value in TreeMap
    static void search(String value)
    {
  
        // Checking for the value
        System.out.println("\nIs value \"" + value
                           + "\" present? "
                           + tree_map.containsValue(value));
    }
  
    // Method 5
    // To display the elements in TreeMap
    static void display()
    {
  
        // Displaying the TreeMap
        System.out.println("\nDisplaying the TreeMap:");
  
        System.out.println("TreeMap: " + tree_map);
    }
  
    // Method 6
    // To traverse TreeMap
    static void traverse()
    {
  
        // Display message only
        System.out.println("\nTraversing the TreeMap:");
  
        for (Map.Entry<Integer, String> e :
             tree_map.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
    }
  
    // Method 6
    // Main driver method
    public static void main(String[] args)
    {
  
        // Calling above defined methods inside main()
  
        // Creating a TreeMap
        create();
  
        // Inserting the 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();
  
        // Traversing the TreeMap
        traverse();
    }
}

Java

// Java Program to Illustrate Addition of Elements
// in TreeMap using put() Method
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Default Initialization of a TreeMap
        TreeMap tm1 = new TreeMap();
  
        // Inserting the elements in TreeMap
        // using put() method
        tm1.put(3, "Geeks");
        tm1.put(2, "For");
        tm1.put(1, "Geeks");
  
        // Initialization of a TreeMap using Generics
        TreeMap<Integer, String> tm2
            = new TreeMap<Integer, String>();
  
        // Inserting the elements in TreeMap
        // again using put() method
        tm2.put(new Integer(3), "Geeks");
        tm2.put(new Integer(2), "For");
        tm2.put(new Integer(1), "Geeks");
  
        // Printing the elements of both TreeMaps
  
        // Map 1
        System.out.println(tm1);
        // Map 2
        System.out.println(tm2);
    }
}

Java

// Java program to Illustrate Updation of Elements
// in TreeMap using put() Method
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the elements in Map
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
  
        // Print all current elements in map
        System.out.println(tm);
  
        // Inserting the element at specified
        // corresponding to specified key
        tm.put(2, "For");
  
        // Printing the updated elements of Map
        System.out.println(tm);
    }
}

Java

// Java program to Illustrate Removal of Elements
// in TreeMap using remove() Method
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the elements
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
        tm.put(4, "For");
  
        // Printing all elements of Map
        System.out.println(tm);
  
        // Removing the element corresponding to key
        tm.remove(4);
  
        //  Printing updated TreeMap
        System.out.println(tm);
    }
}

Java

// Java Program to Illustrate Iterating over TreeMap
// using
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a TreeMap
        // using Generics
        TreeMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the elements
        // using put() method
        tm.put(3, "Geeks");
        tm.put(2, "For");
        tm.put(1, "Geeks");
  
        // For-each loop for traversal over Map
        // via entrySet() Method
        for (Map.Entry mapElement : tm.entrySet()) {
  
            int key = (int)mapElement.getKey();
  
            // Finding the value
            String value = (String)mapElement.getValue();
  
            // Printing the key and value
            System.out.println(key + " : " + value);
        }
    }
}

Publicación traducida automáticamente

Artículo escrito por srinjoy_santra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *