Map相关内容

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

posted @ 2017-07-27 14:53  wc_nan  阅读(327)  评论(0编辑  收藏  举报