Java集合框架学习(九) TreeMap详解

TreeMap介绍


TreeMap 类实现了Map接口,和HashMap类类似。

TreeMap是一个基于Red-Black tree的可导航map的实现。 它基于key的自然顺序排序。

TreeMap和HashMap在排序上。

TreeMap是非线程同步的。



类定义


public class TreeMap<K,V>
extends AbstractMap<K,V>

implements NavigableMap<K,V>, Cloneable, Serializable



例子介绍


package com.dylan.collection;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author xusucheng
 * @create 2018-02-03
 **/
public class TreeMapExample {
    public static void main(String args[]) {

      /* This is how to declare TreeMap */
        TreeMap<Integer, String> tmap =
                new TreeMap<>();

      /*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());
        }

    }
}





如何让TreeMap按value排序


package com.dylan.collection;

import java.util.*;

/**
 * @author xusucheng
 * @create 2018-02-03
 **/
public class TreeMapSortByValue {
    //Method for sorting the TreeMap based on values
    public static <K, V extends Comparable<V>> Map<K, V>
    sortByValues(final Map<K, V> map) {
        Comparator<K> valueComparator =
                new Comparator<K>() {
                    public int compare(K k1, K k2) {
                        int compare =
                                map.get(k1).compareTo(map.get(k2));
                        if (compare == 0)
                            return 1;
                        else
                            return compare;
                    }
                };

        Map<K, V> sortedByValues =
                new TreeMap<K, V>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }
    public static void main(String args[]) {

        TreeMap<String, String> treemap = new TreeMap<String, String>();

        // Put elements to the map
        treemap.put("Key1", "Jack");
        treemap.put("Key2", "Rick");
        treemap.put("Key3", "Kate");
        treemap.put("Key4", "Tom");
        treemap.put("Key5", "Steve");

        // Calling the method sortByvalues
        Map sortedMap = sortByValues(treemap);

        // Get a set of the entries on the sorted map
        Set set = sortedMap.entrySet();

        // Get an iterator
        Iterator i = set.iterator();

        // Display elements
        while(i.hasNext()) {
            Map.Entry me = (Map.Entry)i.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
    }
}



如何让TreeMap按Key倒序迭代

package com.dylan.collection;

import java.util.*;

/**
 * @author xusucheng
 * @create 2018-02-03
 **/
public class TreeMapOrderByKeyDesc {
    public static void main(String args[]) {

        Map<String, String> treemap =
                new TreeMap<String, String>(Collections.reverseOrder());

        // Put elements to the map
        treemap.put("Key1", "Jack");
        treemap.put("Key2", "Rick");
        treemap.put("Key3", "Kate");
        treemap.put("Key4", "Tom");
        treemap.put("Key5", "Steve");

        Set set = treemap.entrySet();
        Iterator i = set.iterator();
        // Display elements
        while(i.hasNext()) {
            Map.Entry me = (Map.Entry)i.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
    }
}




如何获取TreeMap的子集



package com.dylan.collection;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author xusucheng
 * @create 2018-02-03
 **/
public class TreeMapSubMap {
    public static void main(String args[]) {

        // Create a TreeMap
        TreeMap<String, String> treemap =
                new TreeMap<String, String>();

        // Put elements to the map
        treemap.put("Key1", "Jack");
        treemap.put("Key2", "Rick");
        treemap.put("Key3", "Kate");
        treemap.put("Key4", "Tom");
        treemap.put("Key5", "Steve");
        treemap.put("Key6", "Ram");

        // Displaying TreeMap elements
        System.out.println("TreeMap Contains : " + treemap);

        // Getting the sub map
    /* public SortedMap<K,V> subMap(K fromKey,K toKey): Returns
     * a view of the portion of this map whose keys range from
     * fromKey, inclusive, to toKey, exclusive.
     * (If fromKey and toKey are equal, the returned map is empty.)
     * The returned map is backed by this map, so changes in the
     * returned map are reflected in this map, and vice-versa.
     * The returned map supports all optional map operations that
     * this map supports.
     */
        SortedMap<String, String> sortedMap = treemap.subMap("Key2","Key5");
        System.out.println("SortedMap Contains : " + sortedMap);

        // Removing an element from Sub Map
        sortedMap.remove("Key4");

    /* Displaying elements of original TreeMap after
     * removing an element from the Sub Map. Since Sub Map is
     * backed up by original Map, the element should be removed
     * from this TreeMap too.
     */
        System.out.println("TreeMap Contains : " + treemap);
    }
}
















posted @ 2018-02-03 10:47  一锤子技术员  阅读(2)  评论(0编辑  收藏  举报  来源