📜  如何在Java中创建 TreeMap?

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

如何在Java中创建 TreeMap?

Java中的TreeMap用于实现 地图界面 NavigableMap以及Abstract Class 。映射根据其键的自然顺序进行排序,或者通过映射创建时提供的Comparator进行排序,具体取决于使用的构造函数。

要创建 TreeMap,我们可以使用Map 类TreeMap 类引用。

示例 1:

Java
// Java program demonstrate how to create a TreeMap
  
import java.util.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        // Declaring a treemap
        TreeMap map;
  
        // Creating an empty TreeMap
        map = new TreeMap();
  
        System.out.println("TreeMap successfully"
                           + " created");
    }
}


Java
// Java program demonstrate how to create and add elements
// to TreeMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating an empty TreeMap using Map interface
        Map map = new TreeMap<>();
        
        System.out.println("TreeMap successfully"
                           + " created");
  
        // Adding elements
        map.put(1, "Geeks");
        map.put(2, "for");
        map.put(3, "Geeks");
  
        // Printing TreeMap
        System.out.println("TreeMap: " + map);
    }
}


输出
TreeMap successfully created

示例 2:

Java

// Java program demonstrate how to create and add elements
// to TreeMap
  
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Creating an empty TreeMap using Map interface
        Map map = new TreeMap<>();
        
        System.out.println("TreeMap successfully"
                           + " created");
  
        // Adding elements
        map.put(1, "Geeks");
        map.put(2, "for");
        map.put(3, "Geeks");
  
        // Printing TreeMap
        System.out.println("TreeMap: " + map);
    }
}
输出
TreeMap successfully created
TreeMap: {1=Geeks, 2=for, 3=Geeks}