package collectionApi;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
public class HashMapApi {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>(10, 0.5f); // 设置初始容量为10 负载系数为0.6
map = new HashMap<>(10); // 设置初始容量为10 负载系数为0.75
map = new HashMap<>(); // 默认初始容量为16 负载系数为0.75
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4"); // 添加键值对
HashMap<String, String> map2 = new HashMap<>(map); // 构造一个相同映射的Map
map2.putAll(map); // 添加map键值对到map2中
int nSize = map.size(); // map 映射数
boolean bIsEmpty = map.isEmpty(); // map 是否为空值
String value = map.get("2"); // key 对应的值 ”2”
boolean bContains = map.containsKey("3"); // 包含key = "3"
bContains = map.containsValue("4"); // 包含 value
value= map.remove("2"); // 移除key值对应的键值对 返回键值对应的value
//System.out.println(value);
map2.clear(); // 清空
Set<String> keySet = map.keySet(); // key 值列表 非 KeySet 而是Map.KeySet 内部类
//System.out.println(keySet); //[1, 3, 4]
Collection<String> list = map.values(); // Map.Values 内部类
Set<Map.Entry<String, String>> entries = map.entrySet();
for(Map.Entry<String, String> entrie : entries) {
//System.out.println(entrie.getKey() + ":" + entrie.getValue());
}
value = map.getOrDefault("5", "1231"); // 没有找到key 对应的value 取默认值
System.out.println(value); // 1231
value = map.putIfAbsent("4", "5"); // 如果存在key 则返回 key 对应的value
//System.out.println(value); // null
//System.out.println(map); // {1=1, 3=3, 4=4}
value = map.putIfAbsent("5", "5"); // 如果不存在key value 关联则添加 且返回null
//System.out.println(value); // null
//System.out.println(map); // {1=1, 3=3, 4=4, 5=5}
boolean b = map.remove("4", "4"); // 仅当key = 4 value = 4 时才删除
//System.out.println(b); // true
//System.out.println(map); // {1=1, 3=3, 5=5}
b = map.replace("3", "3", "33"); // key = 3 value = 3 value值替换为 33
//System.out.println(b); // true
//System.out.println(map); // {1=1, 3=33, 5=5}
value = map.replace("3", "44"); // 替换为44 如果没有key 则返回null
System.out.println(value); // 33
System.out.println(map); // {1=1, 3=44, 5=5}
map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String t, String u) {
System.out.println(t + ":" + u);
}
});
}
}
HashMap 详解
最新推荐文章于 2022-03-09 15:20:28 发布