HashMap的常见用法

导言:
后台开发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());
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值