📜  Java中的树形图

📅  最后修改于: 2022-05-13 01:54:59.196000             🧑  作者: Mango

Java中的树形图

Java中的 TreeMap 用于实现 Map 接口和 NavigableMap 以及 AbstractMap 类。地图根据其键的自然顺序排序,或者由地图创建时提供的比较器排序,具体取决于使用的构造函数。这被证明是排序和存储键值对的一种有效方式。树图维护的存储顺序必须与 equals 一致,就像任何其他排序图一样,与显式比较器无关。树图实现在某种意义上是不同步的,如果一个映射被多个线程同时访问,并且至少一个线程在结构上修改了映射,则它必须在外部同步。

树形图的特点

树形图的一些重要特征如下:

  1. 此类是Java集合框架的成员。
  2. 该类实现了包括 NavigableMap、SortedMap 在内的 Map 接口,并扩展了 AbstractMap 类。
  3. Java中的 TreeMap 不允许空键(如 Map),因此会引发 NullPointerException。但是,多个空值可以与不同的键相关联。
  4. 此类中的方法及其视图返回的条目对表示映射在生成时的快照。它们不支持 Entry.setValue 方法。

现在让我们继续讨论 Synchronized TreeMap。 TreeMap 的实现是不同步的。这意味着如果多个线程同时访问一个树集,并且至少有一个线程修改了该集,则它必须在外部同步。这通常通过使用 Collections.synchronizedSortedMap 方法来完成。这最好在创建时完成,以防止对集合的意外不同步访问。这可以这样做:

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)); 

极客们,现在您一定想知道 TreeMap 在内部是如何工作的?

TreeMap 中的方法在获取键集和值时,返回一个本质上快速失败的迭代器。因此,任何并发修改都会抛出 ConcurrentModificationException。 TreeMap 基于红黑树数据结构。

树中的每个节点都有:

  • 3个变量( K键=键,V值=值,布尔颜色=颜色
  • 3 个参考(条目左侧 = 左侧,条目右侧 = 右侧,条目父级 = 父级

TreeMap 中的构造函数

为了创建 TreeMap,我们需要创建 TreeMap 类的对象。 TreeMap 类由允许创建 TreeMap 的各种构造函数组成。以下是此类中可用的构造函数:

  1. 树图()
  2. TreeMap(比较器比较)
  3. TreeMap(地图M)
  4. TreeMap(SortedMap sm)

让我们在实现每个构造函数的同时单独讨论它们,如下所示:

构造函数 1: TreeMap()

此构造函数用于构建一个空树形图,该树形图将使用其键的自然顺序进行排序。

例子

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 tree_map
            = new TreeMap();
 
        // 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 {
 
    // 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 tree_map
            = new TreeMap(
                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
    static void Example3rdConstructor()
    {
        // Creating an empty HashMap
        Map hash_map
            = new HashMap();
 
        // 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 tree_map
            = new TreeMap(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 sorted_map
            = new ConcurrentSkipListMap();
 
        // 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 tree_map
            = new TreeMap(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 tree_map;
 
    // Method 1
    // To create TreeMap
    static void create()
    {
 
        // Creating an empty TreeMap
        tree_map = new TreeMap();
 
        // 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 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 tm2
            = new TreeMap();
 
        // 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 tm
            = new TreeMap();
 
        // 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 tm
            = new TreeMap();
 
        // 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 tm
            = new TreeMap();
 
        // 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);
        }
    }
}


输出:
TreeMap using TreeMap() constructor:
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

构造函数 2: TreeMap(Comparator comp)

此构造函数用于构建一个空的 TreeMap 对象,其中的元素需要一个外部规范的排序顺序。

例子

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 {
 
    // 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 tree_map
            = new TreeMap(
                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();
    }
}
输出:
TreeMap using TreeMap(Comparator) constructor:
TreeMap: {111 bbbb london=2, 121 cccc jaipur=1, 131 aaaa nyc=3}

构造函数3: TreeMap(Map M)

此构造函数用于使用给定映射 M 中的条目初始化 TreeMap,将使用键的自然顺序对其进行排序。

例子

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
    static void Example3rdConstructor()
    {
        // Creating an empty HashMap
        Map hash_map
            = new HashMap();
 
        // 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 tree_map
            = new TreeMap(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();
    }
}
输出:
TreeMap using TreeMap(Map) constructor:
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

构造函数4: TreeMap(SortedMap sm)

此构造函数用于使用给定排序映射中的条目初始化 TreeMap,这些条目将以与给定排序映射相同的顺序存储。

例子

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 sorted_map
            = new ConcurrentSkipListMap();
 
        // 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 tree_map
            = new TreeMap(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();
    }
}
输出:
TreeMap using TreeMap(SortedMap) constructor:
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}

TreeMap 类中的方法

MethodAction Performed
clear()The method removes all mappings from this TreeMap and clears the map.
clone()The method returns a shallow copy of this TreeMap.
containsKey(Object key)Returns true if this map contains a mapping for the specified key.
containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a set view of the mappings contained in this map.
firstKey()Returns the first (lowest) key currently in this sorted map.
get(Object key)Returns the value to which this map maps the specified key.
headMap(Object key_value)The method returns a view of the portion of the map strictly less than the parameter key_value.
keySet()The method returns a Set view of the keys contained in the treemap.
lastKey()Returns the last (highest) key currently in this sorted map.
put(Object key, Object value)The method is used to insert a mapping into a map.
putAll(Map map)Copies all of the mappings from the specified map to this map.
remove(Object key)Removes the mapping for this key from this TreeMap if present.
size()Returns the number of key-value mappings in this map.
subMap((K startKey, K endKey)The method returns the portion of this map whose keys range from startKey, inclusive, to endKey, exclusive.
values()Returns a collection view of the values contained in this map.

实现:下面的程序将更好地演示如何创建、插入和遍历 TreeMap。

插图:

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 tree_map;
 
    // Method 1
    // To create TreeMap
    static void create()
    {
 
        // Creating an empty TreeMap
        tree_map = new TreeMap();
 
        // 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 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();
    }
}
输出:
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

在 TreeMap 上执行各种操作

在Java 1.5 中引入泛型之后,可以限制 TreeMap 中可以存储的对象类型。现在,让我们看看如何在 TreeMap 上执行一些常用的操作。

操作 1:添加元素

为了向 TreeMap 添加元素,我们可以使用 put() 方法。但是,插入顺序不会保留在 TreeMap 中。在内部,对于每个元素,键都会按升序进行比较和排序。

例子

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 tm2
            = new TreeMap();
 
        // 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);
    }
}
输出:
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

操作 2:更改元素

添加元素后,如果我们希望更改元素,可以通过使用 put() 方法再次添加元素来完成。由于树图中的元素是使用键索引的,因此可以通过简单地插入我们希望更改的键的更新值来更改键的值。

例子

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 tm
            = new TreeMap();
 
        // 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);
    }
}
输出:
{1=Geeks, 2=Geeks, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

操作 3:移除元素

为了从 TreeMap 中删除一个元素,我们可以使用 remove() 方法。此方法获取键值并从该树形图中删除该键的映射(如果它存在于映射中)。

例子

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 tm
            = new TreeMap();
 
        // 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);
    }
}
输出:
{1=Geeks, 2=Geeks, 3=Geeks, 4=For}
{1=Geeks, 2=Geeks, 3=Geeks}

操作 4:遍历 TreeMap

有多种方法可以遍历 Map。最著名的方法是使用 for-each 循环并获取密钥。键的值是通过使用getValue() 方法找到的。

例子

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 tm
            = new TreeMap();
 
        // 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);
        }
    }
}
输出:
1 : Geeks
2 : For
3 : Geeks