Java基础之:Map——TreeMap

 

 

Java基础之:Map——TreeMap

TreeMap简单介绍

TreeMap实现了Map的子接口SorteMap。

而TreeMap与TreeSet一样,可以自己指定元素如何排列。TreeMap可以实现提供的比较机制。

使用案例

package class_Map;
​
import java.util.Comparator;
import java.util.TreeMap;
​
public class ClassTest04_TreeMap {
​
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 比如 String -key String -val
        // 希望 key 按照 长度 的从大到小
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                // TODO Auto-generated method stub
                return ((String) o2).length() - ((String) o1).length();
            }
        });
​
        map.put("111", "hello01");
        map.put("22222", "hello02");
        map.put("33", "hello03");
        map.put("3666", "hello05");
        map.put("4", "hello02");
        map.put("5", null);
        System.out.println(map);
    }
​
}

程序输出

{22222=hello02, 3666=hello05, 111=hello01, 33=hello03, 4=null}

posted @ 2020-12-27 08:44  奋斗的小范同学  阅读(219)  评论(0编辑  收藏  举报