61 java集合和泛型_11 _Map体系集合
Map体系集合
Map父接口
- 特点:存储一对数据(Key-Value), 无序、无下标,键不可重复,值可重复。
- 方法:
- V put(K key,V value) //将对象存入到集合中,关联键值。key重复则覆盖原值。
- 0bject get (Object key) //根据键获取对应的值。
- Set keySet() //返回所有key。【重点】
- Collection values() //返回包含所有值的Col lection集合。
- Set<Map. Entry<K, V>> entrySet() //返回键值匹配的Set集合。【重点】
代码:
package com.wlw.collection.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Map集合的使用
* 特点:存储一对数据(Key-Value), 无序、无下标,键不可重复,值可重复。
*/
public class Map_Demo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
//1.添加
map.put("cn","中国");
map.put("uk","英国");
map.put("usa","美国");
//map.put("cn","zhongguo"); //这会覆盖上面的 map.put("cn","中国");
System.out.println("元素个数:"+map.size());
System.out.println(map.toString());
//2.删除
/*
map.remove("usa");//通过键来删除
System.out.println("删除之后,元素个数:"+map.size());
*/
//3.遍历
//3.1使用 keySet() 返回一个只包含键的set集合
System.out.println("-------------3.1使用 keySet()----------------");
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key+"--->"+map.get(key));
}
/*
for(String key : map.keySet()){
System.out.println(key+":"+map.get(key));
}
*/
//3.2使用 entrySet() 返回一个包含entry的set集合(这个方法遍历效率更高)
System.out.println("-------------3.2使用 entrySet()----------------");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
/*
for(Map.Entry<String,String> entry: map.entrySet()){
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
*/
//4.判断
System.out.println(map.containsKey("cn"));//true
System.out.println(map.containsValue("泰国"));//false
System.out.println(map.isEmpty());//false
}
}
/*
元素个数:3
{usa=美国, uk=英国, cn=中国}
-------------3.1使用 keySet()----------------
usa--->美国
uk--->英国
cn--->中国
-------------3.2使用 entrySet()----------------
usa--->美国
uk--->英国
cn--->中国
true
false
false
*/