TreeMap
TreeMap实现了Map接口,基于红黑树(Red-Black tree)实现,是一个有序的key-value集合。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
构造方法
1.TreeMap()
创建一个空的tree map,按照keys的自然顺序
-
TreeMap(Comparator<? super K> comparator)
创建一个空的tree map,按照给定comparator的顺序 -
TreeMap(Map<? extends K, ? extends V> m)
创建包含给定map的新tree map,按照keys的自然顺序 -
TreeMap(SortMap<K, ? extends V> m)
创建包含给定map的新tree map,按照给定map的顺序排序
常用方法
void |
clear() Removes all of the mappings from this map. |
---|---|
Object |
clone() Returns a shallow copy of this TreeMap instance. |
V |
put(K key, V value) Associates the specified value with the specified key in this map. |
boolean |
containsKey(Object key) Returns true if this map contains a mapping for the specified key. |
boolean |
containsValue(Object value) Returns true if this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> |
entrySet() Returns a Set view of the mappings contained in this map. |
V |
get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
Set<K> |
keySet() Returns a Set view of the keys contained in this map. |
Map.Entry<K,V> |
lastEntry() Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. |
V |
remove(Object key) Removes the mapping for this key from this TreeMap if present. |
int |
size() Returns the number of key-value mappings in this map. |
Collection<V> |
values() Returns a Collection view of the values contained in this map. |
遍历
- for循环遍历
for (Map.Entry entry : mapCollection.entrySet()) {
// other code
}
- Iterator遍历
Set set = mapCollection.entrySet();
Iterator iterator = mapCollection.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
// other code
}
举个栗子
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();
tmap.put(1, "apple");
tmap.put(3, "banana");
tmap.put(24, "cat");
tmap.put(12, "dog");
tmap.put(10, "egg");
tmap.put(15, "fish");
for (Map.Entry entry : tmap.entrySet()) {
System.out.printf("key is " + entry.getKey()+" ");
System.out.println("value is " + entry.getValue());
}
Set set = tmap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
System.out.printf("key is " + entry.getKey()+" ");
System.out.println("value is " + entry.getValue());
}
}
}
运行结果:
key is 1 value is apple
key is 3 value is banana
key is 10 value is egg
key is 12 value is dog
key is 15 value is fish
key is 24 value is cat
网友评论