导言:
后台开发Map和List的使用是家常便饭了,不过今天只是做个笔记,说下HashMap的日常使用方法
知识点:
//基本使用:
Map<String,String> map=new HashMap<>();
map.put("aile1", "test01");
map.put("aile2", "test02");
System.out.println(map.get("aile1"));//获取值
System.out.println(map.remove("aile2"));//删除
System.out.println(map.size());//大小
System.out.println(map.isEmpty());//空判定
System.out.println(map.containsKey("aile2"));//键判定
System.out.println(map.containsValue("test02"));//值判定
//getOrDefault,指定返回默认值,有key使用key值,没key使用指定默认
Map<String,String> map=new HashMap<>();
map.put("aile1", "test01");
map.put("aile2", "test02");
System.out.println(map.getOrDefault("aile1", "test"));//test01
System.out.println(map.getOrDefault("aile3", "test03"));//test03
//putIfAbsent,key不存在会插入
Map<String,String> map=new HashMap<>();
map.put("aile1", "test01");
map.put("aile2", "test02");
map.putIfAbsent("aile2", "test");//不插入
map.putIfAbsent("aile3", "test03");//插入
//replace,key存在会插入
Map<String,String> map=new HashMap<>();
map.put("aile1", "test01");
map.put("aile2", "test02");
map.replace("aile2", "newTest02");//替换
map.replace("aile3", "test03");//不替换
//排序:
HashMap<Integer,String> hashMap = new HashMap<>();
hashMap.put(4,"dd");
hashMap.put(3,"cc");
hashMap.put(2,"bb");
hashMap.put(1,"aa");
ArrayList<Integer> list= new ArrayList<>(hashMap.keySet());
Collections.sort(list, (o1, o2) -> o1>o2?1:-1);
//遍历效率:
//普遍,1万以下使用
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//大数据,1万以上使用
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}