Map集合
Map集合是接口,是将键映射到值得对象,不包含重复的键,每个键可以映射到最多一个值。
创建Map集合的对象:
- 多态的方式
- 具体的实现类HashMap
基本操作
public class MapDemo1 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
//V put(K key, V value) 将指定的值与该映射中的指定键相关联,添加元素
map.put("password1", "123");
map.put("password2", "456");
//V remove(Object key) 根据键删除键值对元素
System.out.println(map.remove("password1"));
//void clear() 移除所有的键值对元素
//boolean containsKey(Object key) 判断集合是否包含指定的键
System.out.println(map.containsKey("password1"));
//boolean containsValue(Object value) 判断集合是否包含指定的值
System.out.println(map.containsValue("456"));
//V get(Object key) 根据键获取值
System.out.println(map.get("password3"));
//Set<K> keySet() 获取所有键的集合
Set<String> keySet = map.keySet();
for (String key: keySet){
System.out.println(key);
}
//Collection<V> value(): 获取所有值的集合
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
//Set<Map.Entry<K,V>> entrySet(); 获取所有键值对对象的集合
Set<Map.Entry<String,String>> entrySet = map.entrySet();
for (Map.Entry<String, String> me : entrySet) {
String key = me.getKey();
String value = me.getValue();
System.out.println(key+","+value);
}
}
}