Map集合:
特点:Map集合的键是无序的,不重复的,无索引的,值没有要求(可以重复)
Map集合后面重复的键对应的值会覆盖前面重复键的值
Map集合的键值对可以为null
HashMap集合常用方法
特点:元素按照键是无序,不重复,无索引,值不做要求(与Map集合一样)
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
//添加集合
maps.put("鞋子",5);
maps.put("手机",2);
maps.put("电脑",2);
maps.put("手表",2);
maps.put("钥匙",2);
maps.put("手机",3);//map集合后面重复添加的键对应的元素会覆盖前面重复的整个元素
System.out.println(maps);
//清空集合
// maps.clear();
System.out.println(maps);
//判断集合是否为空
System.out.println(maps.isEmpty());
//根据键获取对应的值
Integer key = maps.get("鞋子");
System.out.println(key);
//根据键删除整个元素
System.out.println(maps.remove("手表1"));
System.out.println(maps);
//判断是否包含了某个键
Boolean b1 = maps.containsKey("手表");
Boolean b2 = maps.containsKey("手机");
System.out.println(b1);
System.out.println(b2);
//判断是否包含了某个值
Boolean b3 = maps.containsValue(23);
Boolean b4 = maps.containsValue(5);
System.out.println(b3);
System.out.println(b4);
//获取到所有的键的集合
Set<String> keys = maps.keySet();
System.out.println(keys);
//获取到所有的值的集合
Collection<Integer> keys1 = maps.values();
System.out.println(keys1);
//获取集合的大小
System.out.println(maps.size());
//合并其他集合
Map<String,Integer> maps1 = new HashMap();
maps1.put("西装",1);
maps1.put("皮鞋",1);
Map<String,Integer> maps2 = new HashMap();
maps2.put("西装",2);
maps2.put("领带",2);
maps1.putAll(maps2);//把maps2中的元素拷贝一份到maps1中去
System.out.println(maps1);
System.out.println(maps2);
遍历方式有三种
public static void main(String[] args) {
Map<String,Integer> maps = new HashMap<>();
maps.put("鞋子",5);
maps.put("手机",2);
maps.put("电脑",2);
maps.put("手表",2);
maps.put("钥匙",2);
System.out.println(maps);
//遍历方式一
Set<String> keys = maps.keySet();
for (String key : keys) {
int value = maps.get(key);
System.out.println(key+"-->"+value);
}
//1.遍历方式二 把Map集合转换成Set集合
Set<Map.Entry<String,Integer>> entries = maps.entrySet();
//2.开始遍历
for (Map.Entry<String,Integer> entry:entries){
String key = entry.getKey();
int value = entry.getValue();
System.out.println(key+"-->"+value);
}
//遍历方式三 (Lambda表达式)
maps.forEach((key,value) -> {
System.out.println(key+"-->"+value);
});
}