JAVA中的Map接口中常用的方法
- Map和Collection没有继承关系
- Map集合以key和value的方式存储数据:键值对
key和value都是引用数据类型,
key和value都是存储对象的内存地址
key起主导作用,value是key的附属品
例子:
Map<Integer, String> map = new HashMap<>();
- V put(K key, V value) 向Map集合中添加键值对
map.put(1,"zhangsan");
map.put(2,"lisi");
map.put(3, "wangwu");
map.put(4,"zhaoliu");
- V get(Object key) 通过key获取value
System.out.println(map.get(3));
- V remove(Object key) 通过key删除对应的键值对
int size() 获取Map集合中键值对的个数
map.remove(2);
System.out.println(map.size());
- boolean containsKey(Object key) 判断Map中是否包含某个key
System.out.println(map.containsKey(3));
- boolean containsValue(Object value) 判断Map中是否包含某个value
System.out.println(map.containsValue("zhangsan"));
- Set keySet() 获取Map集合所有的key(所有的键是一个set集合,返回一个Set集合)
Set<Integer> set = map.keySet();
Iterator<Integer> it1 = set.iterator();
while (it1.hasNext()){
Integer key = it1.next();
String value = map.get(key);
System.out.println("key = " + key + ",value = " + value);
}
for (Integer s : set) {
System.out.println("key = " + s + ",value = " + map.get(s));
}
System.out.println("==============================");
- Collection values() 获取Map集合中所有的value,返回一个Collection集合
Collection<String> collection = map.values();
for (String str : collection) {
System.out.println(str);
}
- Set<Map.Entry<K,V>> entrySet() 将Map集合转换成Set集合
Map.Entry为Map类的静态内部类
Set<Map.Entry<Integer, String>> set1 = map.entrySet();
for (Map.Entry<Integer, String> node: set1) {
System.out.println("key = " + node.getKey() + ",value = " + node.getValue());
}
- void clear() 清空Map集合
boolean isEmpty() 判断Map集合中元素个数是否为0
map.clear();
System.out.println(map.isEmpty());