TreeMap类实现类似于HashMap的Map接口。 TreeMap是SortedMap的一个示例,即可以对键的顺序进行排序。

在下面的例子中,我们将展示TreeMap类的各种方法。如下:

  • put() - 将键和值添加到Map中。
  • get() - 通过传递键返回值。
  • remove() - 从Map中删除键和值。
  • size() - 返回Map的大小。
  • containsKey() - 如果key存在于Map中则返回true,否则返回false。
  • containsValue() - 如果Map中存在value则返回true,否则返回false。
  • clear() - 从Map中删除所有元素。

文件:TreeMapExample.java -

package com.yiibai.tutorial;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author yiibai
 *
 */
public class TreeMapExample {
    public static void main(String[] args) {
        Map<String String> map=new TreeMap<>();
        /*Adding key and values in TreeMap*/
        map.put("1" "One");
        map.put("2" "Two");
        map.put("3""Three");
        map.put("4" "Four");
        map.put("5" "Five");

        System.out.println("TreeMap key-values:"+map);

        /*Get value by key from the TreeMap*/
        System.out.println("Value of '4' is: "+map.get("4"));

        /*Removing key and value from the TreeMap    */
        map.remove("4");
        System.out.println("After removal TreeMap Key-Value: " +map);

        /*Getting size of TreeMap*/
        System.out.println("Size of TreeMap is : "+map.size());

        /*Checking if key exist in the TreeMap or not*/
        System.out.println("Key '3' exist: "+map.containsKey("3"));

        /*Checking if value exist in the TreeMap or not*/
        System.out.println("Key '6' exist: "+map.containsValue("6"));

        /*Remove all keys and values from the TreeMap*/
        map.clear();
        System.out.println("After clearing map: "+map);
    }
}

执行上面示例代码,得到以下结果:

TreeMap key-values:{1=One 2=Two 3=Three 4=Four 5=Five}
Value of '4' is: Four
After removal TreeMap Key-Value: {1=One 2=Two 3=Three 5=Five}
Size of TreeMap is : 4
Key '3' exist: true
Key '6' exist: false
After clearing map: {}