1. 程式人生 > >Map相關內容

Map相關內容

void put println val ret entryset con ati 多少

Map 方法
Map 是一個 接口 public interface Map<K,V>
裏面的方法有:
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(Object key);
V put(K key, V value);
V remove(Object key);
void putAll(Map<? extends K, ? extends V> m);
void clear();
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
boolean equals(Object o);
int hashCode();
......
interface Entry<K,V> { Entry為Map接口中的內部接口
提供 方法有:
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();

public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}

public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}

public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}

public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
}


int size(); 方法是檢索Map集合中包含多少條數據

boolean isEmpty();
該方法判斷Map集合對象是否包含內容,也就是判斷該Map集合容器是不是空的。
該方法返回值為bolean對象,如果Map集合對象不包含任何內容,則返回true,否則返回false。

boolean containsKey(Object key);
該方法判斷Map集合對象中是否包含指定的鍵名。如果Map集合中包含指定的鍵名,則返回true,否則返回false。

boolean containsValue(Object value);
該方法判斷Map集合中是否包含指定的鍵值。如果Map集合中包含指定的鍵值對象,則返回true,否則返回false。
value:要查詢的Map集合的指定鍵值對象

V get(Object key);
根據指定的鍵 找出對應的值

V put(K key, V value);
添加一個鍵值對

V remove(Object key);
根據 Map中的鍵 刪除鍵值對

void putAll(Map<? extends K, ? extends V> m);
該方法用來追加另一個Map對象到當前Map集合對象,它會把另一個Map集合對象中的所有內容添加到當前Map集合對象。
結論:putAll可以合並兩個MAP,只不過如果有相同的key那麽用後面的覆蓋前面的

void clear()
Map.clear方法——從Map集合中移除所有映射關系。執行該方法後,該集合對象的映射內容將為空。


Set<K> keySet();
該方法將獲取Map集合的所有鍵名,並存放在一個Set集合對象中。

遍歷Map的方式: Map.Entry 和 Map.entrySet()
Map<String,String> map=new HashMap<String,String>();
map.put("1", "張三");
map.put("2", "李四");
map.put("3", "王五");

System.out.println("方法一:");
Iterator iterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry= (Entry<String, String>) iterator.next();
System.out.println("key:"+entry.getKey()+" value"+entry.getValue());
}

System.out.println("方法二:");
for (Map.Entry<String, String> m : map.entrySet()) {
System.out.println("key:"+m.getKey()+" value"+m.getValue());
}
}
}

Map相關內容