Map集合概述和特点:
interface Map<K,V> K:键的类型;V:值的类型
Map集合的特点:
- 双列集合,一个键对应一个值
- 键不可以重复,值可以重复
Map集合的方法:
public static void main(String[] args) {
Map<String,Integer> map = new HashMap ();
map.put ("s",1);
map.put ("w",5);
map.put ("d",8);
map.put ("a",2);
System.out.println (map);
//获取键
Integer s = map.get ("s");
System.out.println (s);
//获取集合的大小
int size = map.size ();
System.out.println (size);
//判断集合里的key值里是否有"s"
if(map.containsKey ("s")){
System.out.println (1);
}
//判断集合里的value元素s是否有"s""
if(map.containsValue ("s")){
System.out.println (1);
}
//判断集合是否为空
if(!map.isEmpty ()){
System.out.println ("ss");
}
}
Map集合的三种遍历的方式:
//一:根据键获取值
Set<String> set = map.keySet ();
for (String s1 : set) {
//根据键获取值
Integer integer = map.get (s1);
System.out.print (s1+integer);
}
System.out.print ("-------------------");
//二:直接获取值元素
Collection<Integer> values = map.values ();
for (Integer value : values) {
System.out.print(value);
}
//三:获取所有键值对对象的集合
Set<Map.Entry<String, Integer>> entries = map.entrySet ();
for (Map.Entry<String, Integer> entry : entries) {
String key = entry.getKey ();
Integer value = entry.getValue ();
System.out.println (key+value);
}
//jdk8新增的entrySet()方法的简易写法
map.forEach ((key,value)->{
System.out.println (key+value);
});