ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java 中的`TreeMap` > 原文: [https://beginnersbook.com/2013/12/treemap-in-java-with-example/](https://beginnersbook.com/2013/12/treemap-in-java-with-example/) `TreeMap`是基于红黑树的`NavigableMap`实现。它根据其键的自然顺序排序。 `TreeMap`类**实现类似于`HashMap`类的`Map`接口。它们之间的主要区别在于[`HashMap`](https://beginnersbook.com/2013/12/hashmap-in-java-with-example/)是一个无序集合,而`TreeMap`按其键的升序排序。`TreeMap`是非同步的集合类,这意味着除非明确同步,否则它不适合线程安全操作。 ## `TreeMap`示例 在这个例子中,我们将键映射和值映射存储到`TreeMap`中,并且我们在从`TreeMap`获取数据时获得排序的键值映射。 ```java import java.util.TreeMap; import java.util.Set; import java.util.Iterator; import java.util.Map; public class Details { public static void main(String args[]) { /* This is how to declare TreeMap */ TreeMap<Integer, String> tmap = new TreeMap<Integer, String>(); /*Adding elements to TreeMap*/ tmap.put(1, "Data1"); tmap.put(23, "Data2"); tmap.put(70, "Data3"); tmap.put(4, "Data4"); tmap.put(2, "Data5"); /* Display content using Iterator*/ Set set = tmap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry mentry = (Map.Entry)iterator.next(); System.out.print("key is: "+ mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); } } } ``` 输出: ```java key is: 1 & Value is: Data1 key is: 2 & Value is: Data5 key is: 4 & Value is: Data4 key is: 23 & Value is: Data2 key is: 70 & Value is: Data3 ``` 正如您所看到的那样,我们已经以随机顺序插入数据,但是当我们显示`TreeMap`内容时,我们按照键的升序获得了排序结果。 #### `TreeMap`教程 以下是`TreeMap`类上发布的教程列表: * [`TreeMap`示例](https://beginnersbook.com/2013/12/treemap-in-java-with-example/ "TreeMap in Java with Example") * [按值排序`TreeMap`](https://beginnersbook.com/2014/07/how-to-sort-a-treemap-by-value-in-java/ "How to sort a TreeMap by value in java") * [`TreeMap`迭代器示例](https://beginnersbook.com/2014/07/treemap-iterator-example-java/) * [以相反的顺序迭代`TreeMap`](https://beginnersbook.com/2014/07/how-to-iterate-treemap-in-reverse-order-in-java/) * [从`TreeMap`获取子映射](https://beginnersbook.com/2014/07/how-to-get-the-sub-map-from-treemap-example-java/) * [获取`TreeMap`的大小](https://beginnersbook.com/2014/07/how-to-get-the-size-of-treemap-example-java/) * [从`TreeMap`中删除键值映射](https://beginnersbook.com/2014/07/remove-key-value-mapping-from-treemap-example/) * [从`TreeMap`中删除所有映射](https://beginnersbook.com/2014/07/remove-all-mappings-from-treemap-example-java/) #### 参考: * [`TreeMap`文档](https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html)