>  기사  >  Java  >  Java 컬렉션의 TreeMap 코드 예

Java 컬렉션의 TreeMap 코드 예

黄舟
黄舟원래의
2017-03-13 14:37:082089검색

TreeMap과 Map의 관계는 다음과 같습니다.



TreeMap 소개:

( 1) TreeMap은 Red-Black Tree를 통해 구현된 Ordered Key-Value Set입니다.

(2) TreeMap은 AbstractMap을 상속하므로 Map이자 키-값 집합입니다.

(3) TreeMap은 Navigable 인터페이스를 구현하고 일련의 탐색 방법을 지원합니다. TreeMap은 순서가 지정된 컬렉션입니다.

(4) Cloneable 인터페이스를 구현하고 복제할 수 있습니다

(5) TreeMap은 직렬화를 지원하는 직렬화 가능 인터페이스를 구현합니다

(6) TreeMap은 레드-블랙 트리 디지털 디스플레이를 기반으로 하며 매핑은 키의 자연스러운 순서에 따라 정렬됩니다


TreeMap 기본 API:


Entrya8093152e673feb7aba1828c43532094                ceilingEntry(K key)
K                          ceilingKey(K key)
clear()
Object                     clone()
Comparatoradea50645660c00d864f8df96cd78b01      comparator()
containsKey(Object key)
NavigableSeta8093152e673feb7aba1828c43532094            descendingKeySet()
NavigableMapa8093152e673feb7aba1828c43532094         descendingMap()
Set<a8093152e673feb7aba1828c43532094>           entrySet()
Entrya8093152e673feb7aba1828c43532094                firstEntry()
K                          firstKey()
Entrya8093152e673feb7aba1828c43532094                floorEntry(K key)
K                          floorKey(K key)
V                          get(Object key)
NavigableMapa8093152e673feb7aba1828c43532094         headMap(K toinclusive)
SortedMapa8093152e673feb7aba1828c43532094            headMap(K toExclusive)
Entrya8093152e673feb7aba1828c43532094                higherEntry(K key)
K                          higherKey(K key)
isEmpty()
Seta8093152e673feb7aba1828c43532094                     keySet()
Entrya8093152e673feb7aba1828c43532094                lastEntry()
K                          lastKey()
Entrya8093152e673feb7aba1828c43532094                lowerEntry(K key)
K                          lowerKey(K key)
NavigableSeta8093152e673feb7aba1828c43532094            navigableKeySet()
Entrya8093152e673feb7aba1828c43532094                pollFirstEntry()
Entrya8093152e673feb7aba1828c43532094                pollLastEntry()
V                          put(K keyV value)
V                          remove(Object key)
size()
SortedMapa8093152e673feb7aba1828c43532094            subMap(K fromInclusiveK toExclusive)
NavigableMapa8093152e673feb7aba1828c43532094         subMap(K fromfromInclusiveK totoInclusive)
NavigableMapa8093152e673feb7aba1828c43532094         tailMap(K frominclusive)
SortedMapa8093152e673feb7aba1828c43532094            tailMap(K fromInclusive)

TreeMap 순회 방법

(1) 다음의 키-값 쌍을 순회합니다. TreeMap: Iterator를 통해 반복적으로 탐색되는 "키-값 쌍"의 컬렉션인 EntrySet()에 따라 TreeMap을 얻습니다.

String key=Integer value=Iterator iterator=map.entrySet().iterator()(iterator.hasNext())
{
    Map.Entry entry=(Map.Entry)iterator.next()    key=(String) entry.getKey()    value=(Integer)entry.getValue()}


(2) TreeMap의 키 순회: keySet()에 따라 설정된 "키"를 얻고, 반복자를 통해 설정된 키를 순회합니다.


String key = Integer integ = Iterator iter = map.keySet().iterator()(iter.hasNext()) {
   key = (String)iter.next()  integ = (Integer)map.get(key)}

(3) TreeMap의 값 순회: 값에 따라 값의 집합을 구하고, Iterator를 통해 값의 집합을 순회합니다.


Integer value = Collection c = map.values()Iterator iter= c.iterator()(iter.hasNext()) 
{
    value = (Integer)iter.next()}

TreeMap 샘플 코드:


public class Hello {
    
    public static void main(String[] args) {
        testTreeMapOridinaryAPIs();
        testSubMapAPIs();
    }
    private static void testTreeMapOridinaryAPIs() {
        // 初始化随机种子
        Random r = new Random();
        // 新建TreeMap
        TreeMap tmap = new TreeMap();
        // 添加操作
        tmap.put("one", r.nextInt(10));
        tmap.put("two", r.nextInt(10));
        tmap.put("three", r.nextInt(10));
        tmap.put("four", r.nextInt(10));
        tmap.put("five", r.nextInt(10));
        tmap.put("six", r.nextInt(10));
        System.out.printf("\n ---- testTreeMapOridinaryAPIs ----\n");
        // 打印出TreeMap
        System.out.printf("%s\n",tmap );
        // 通过Iterator遍历key-value
        Iterator iter = tmap.entrySet().iterator();
        while(iter.hasNext()) {
            Map.Entry entry = (Map.Entry)iter.next();
            System.out.printf("next : %s - %s\n", entry.getKey(), entry.getValue());
        }
        // TreeMap的键值对个数        
        System.out.printf("size: %s\n", tmap.size());
        // containsKey(Object key) :是否包含键key
        System.out.printf("contains key two : %s\n",tmap.containsKey("two"));
        System.out.printf("contains key five : %s\n",tmap.containsKey("five"));
        // containsValue(Object value) :是否包含值value
        System.out.printf("contains value 0 : %s\n",tmap.containsValue(new Integer(0)));
        // remove(Object key) : 删除键key对应的键值对
        tmap.remove("three");
        System.out.printf("tmap:%s\n",tmap );
        // clear() : 清空TreeMap
        tmap.clear();
        // isEmpty() : TreeMap是否为空
        System.out.printf("%s\n", (tmap.isEmpty()?"tmap is empty":"tmap is not empty") );
    }
    public static void testSubMapAPIs() {
        // 新建TreeMap
        TreeMap tmap = new TreeMap();
        // 添加“键值对”
        tmap.put("a", 101);
        tmap.put("b", 102);
        tmap.put("c", 103);
        tmap.put("d", 104);
        tmap.put("e", 105);
        System.out.printf("\n ---- testSubMapAPIs ----\n");
        // 打印出TreeMap
        System.out.printf("tmap:\n\t%s\n", tmap);
        // 测试 headMap(K toKey)
        System.out.printf("tmap.headMap(\"c\"):\n\t%s\n", tmap.headMap("c"));
        // 测试 headMap(K toKey, boolean inclusive) 
        System.out.printf("tmap.headMap(\"c\", true):\n\t%s\n", tmap.headMap("c", true));
        System.out.printf("tmap.headMap(\"c\", false):\n\t%s\n", tmap.headMap("c", false));
        // 测试 tailMap(K fromKey)
        System.out.printf("tmap.tailMap(\"c\"):\n\t%s\n", tmap.tailMap("c"));
        // 测试 tailMap(K fromKey, boolean inclusive)
        System.out.printf("tmap.tailMap(\"c\", true):\n\t%s\n", tmap.tailMap("c", true));
        System.out.printf("tmap.tailMap(\"c\", false):\n\t%s\n", tmap.tailMap("c", false));
        // 测试 subMap(K fromKey, K toKey)
        System.out.printf("tmap.subMap(\"a\", \"c\"):\n\t%s\n", tmap.subMap("a", "c"));
        // 测试 
        System.out.printf("tmap.subMap(\"a\", true, \"c\", true):\n\t%s\n",
                tmap.subMap("a", true, "c", true));
        System.out.printf("tmap.subMap(\"a\", true, \"c\", false):\n\t%s\n",
                tmap.subMap("a", true, "c", false));
        System.out.printf("tmap.subMap(\"a\", false, \"c\", true):\n\t%s\n",
                tmap.subMap("a", false, "c", true));
        System.out.printf("tmap.subMap(\"a\", false, \"c\", false):\n\t%s\n",
                tmap.subMap("a", false, "c", false));

        // 测试 navigableKeySet()
        System.out.printf("tmap.navigableKeySet():\n\t%s\n", tmap.navigableKeySet());
        // 测试 descendingKeySet()
        System.out.printf("tmap.descendingKeySet():\n\t%s\n", tmap.descendingKeySet());
    }
    public static void testNavigableMapAPIs() {
        // 新建TreeMap
        NavigableMap nav = new TreeMap();
        // 添加“键值对”
        nav.put("aaa", 111);
        nav.put("bbb", 222);
        nav.put("eee", 333);
        nav.put("ccc", 555);
        nav.put("ddd", 444);

        System.out.printf("\n ---- testNavigableMapAPIs ----\n");
        // 打印出TreeMap
        System.out.printf("Whole list:%s%n", nav);

        // 获取第一个key、第一个Entry
        System.out.printf("First key: %s\tFirst entry: %s%n",nav.firstKey(), nav.firstEntry());

        // 获取最后一个key、最后一个Entry
        System.out.printf("Last key: %s\tLast entry: %s%n",nav.lastKey(), nav.lastEntry());

        // 获取“小于/等于bbb”的最大键值对
        System.out.printf("Key floor before bbb: %s%n",nav.floorKey("bbb"));

        // 获取“小于bbb”的最大键值对
        System.out.printf("Key lower before bbb: %s%n", nav.lowerKey("bbb"));

        // 获取“大于/等于bbb”的最小键值对
        System.out.printf("Key ceiling after ccc: %s%n",nav.ceilingKey("ccc"));

        // 获取“大于bbb”的最小键值对
        System.out.printf("Key higher after ccc: %s%n\n",nav.higherKey("ccc"));
    }

}

실행 결과:

---- testTreeMapOridinaryAPIs ----
{five=5, four=5, one=3, six=8, three=1, two=0}
next : five - 5
next : four - 5
next : one - 3
next : six - 8
next : three - 1
next : two - 0
size: 6
contains key two : true
contains key five : true
contains value 0 : true
tmap:{five=5, four=5, one=3, six=8, two=0}
tmap is empty
 ---- testSubMapAPIs ----
tmap:
 {a=101, b=102, c=103, d=104, e=105}
tmap.headMap("c"):
 {a=101, b=102}
tmap.headMap("c", true):
 {a=101, b=102, c=103}
tmap.headMap("c", false):
 {a=101, b=102}
tmap.tailMap("c"):
 {c=103, d=104, e=105}
tmap.tailMap("c", true):
 {c=103, d=104, e=105}
tmap.tailMap("c", false):
 {d=104, e=105}
tmap.subMap("a", "c"):
 {a=101, b=102}
tmap.subMap("a", true, "c", true):
 {a=101, b=102, c=103}
tmap.subMap("a", true, "c", false):
 {a=101, b=102}
tmap.subMap("a", false, "c", true):
 {b=102, c=103}
tmap.subMap("a", false, "c", false):
 {b=102}
tmap.navigableKeySet():
 [a, b, c, d, e]
tmap.descendingKeySet():
 [e, d, c, b, a]

Java8 기반 SortedMap 인터페이스 소스 코드:

public interface SortedMapb77a8d9c3c319e50d4b02a976b347910 extends Mapb77a8d9c3c319e50d4b02a976b347910 {
    Comparator99be4058f294b5c4a6207ddd3216ce19 comparator();
    SortedMapb77a8d9c3c319e50d4b02a976b347910 subMap(K fromKey, K toKey);
    SortedMapb77a8d9c3c319e50d4b02a976b347910 headMap(K toKey);
    SortedMapb77a8d9c3c319e50d4b02a976b347910 tailMap(K fromKey);
    K firstKey();
    K lastKey();
    Set245c3adc26563b673f7297c0b3777639 keySet();
    Collectiond94943c0b4933ad8cac500132f64757f values();
    Set3b0b8c50db3add957fd22f5a448ffe65> entrySet();
}

Java8 기반 탐색 가능한 인터페이스 소스 코드:


public interface NavigableMapb77a8d9c3c319e50d4b02a976b347910 extends SortedMapb77a8d9c3c319e50d4b02a976b347910 {
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 lowerEntry(K key);
    K lowerKey(K key);
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 floorEntry(K key);
    K floorKey(K key);
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 ceilingEntry(K key);
    K ceilingKey(K key);
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 higherEntry(K key);
    K higherKey(K key);
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 firstEntry();
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 lastEntry();
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 pollFirstEntry();
    Map.Entryb77a8d9c3c319e50d4b02a976b347910 pollLastEntry();
    NavigableMapb77a8d9c3c319e50d4b02a976b347910 descendingMap();
    NavigableSet245c3adc26563b673f7297c0b3777639 navigableKeySet();
    NavigableSet245c3adc26563b673f7297c0b3777639 descendingKeySet();
    NavigableMapb77a8d9c3c319e50d4b02a976b347910 subMap(K fromKey, boolean fromInclusive,
                             K toKey,   boolean toInclusive);
    NavigableMapb77a8d9c3c319e50d4b02a976b347910 headMap(K toKey, boolean inclusive);
    NavigableMapb77a8d9c3c319e50d4b02a976b347910 tailMap(K fromKey, boolean inclusive);
    SortedMapb77a8d9c3c319e50d4b02a976b347910 subMap(K fromKey, K toKey);
    SortedMapb77a8d9c3c319e50d4b02a976b347910 headMap(K toKey);
    SortedMapb77a8d9c3c319e50d4b02a976b347910 tailMap(K fromKey);
}

Java8 기반 TreeMap 소스 코드:


아아아

위 내용은 Java 컬렉션의 TreeMap 코드 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.