HashMap方法练习
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* HashMap训练,无序
* LinkedHashMap与这个用法一样,是有序的
*/
public class Test01 {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("柯南",8);
map.put("步美",7);
map.put("灰原哀",8);
map.put("毛利小五郎",42);
//添加2
//如果有该key就不添加,返回在集合中的value,它是不会覆盖原有value的
//如果没有key,就添加k-v
Integer ifAbsent = map.putIfAbsent("毛利小五郎", 56);
//添加3
//将新集合中所有的元素添加到map集合中
HashMap<String,Integer> newMap1 = new HashMap<>();
newMap1.put("aaa", 10);
newMap1.put("bbb", 20);
newMap1.put("ccc", 30);
map.putAll(newMap1);//
Integer integer1 = map.put("阿笠博士", 78);
System.out.println(integer1);//第一次是添加返回null
//第二次put相同键,是替换,返回上一次的value
map.put("阿笠博士",89);
//替换2
Integer replace = map.replace("柯南", 1);
System.out.println("返回替换前的value值:"+replace);
//替换3
map.replace("灰原哀",8,10);//返回的是boolean值
//map.clear();
//清空
//判断是否存在某key
boolean b1 = map.containsKey("毛利小五郎");
//判断是否存在某value
boolean b2 = map.containsValue(42);
//通过键获取值
Integer value1 = map.get("步美");
map.getOrDefault("步美",888);
//键存在返回value,不存在返回默认值888
System.out.println("---------------");
//遍历1 - keySet()
//找出所有键的集合,根据键获取值
Set<String> keySet = map.keySet();
for(String key:keySet){
Integer value = map.get(key);
System.out.println(key +" -- "+value);
}
System.out.println("------------------");
//遍历2 - entrySet()
//找出每个键值对,将键值对存进Set里,
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry<String, Integer> kv:entrySet){
System.out.println(kv.getKey()+" -- "+kv.getValue());
}
}
}