HashMap 详解

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);
					}
		});
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值