HashMap常用方法

public static void main(String[] args) {
         HashMap<Integer,String> map=new HashMap<>();
         //下面放方法
     }

1.存值 put(key, value):

HashMap<Integer, String> map = new HashMap<>();
//向map中添加值(返回这个key以前的value,如果没有返回null)
System.out.println(map.put(1, "jack"); // null
System.out.println(map.put(1, "candy"); // jack

2.取值 get(key):

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "bella");
// 得到map中key相对应的value的值
System.out(map.get(1)); // "bella"
System.out(map.get("bella"); // null

3.判断是否为空 map.isEmpty():

HashMap<Integer, String> map = new HashMap<>();
// 判断map是否为空
System.out.println(map.isEmpty()); // true
map.put(1, "Jessica");
System.out.println(map.isEmpty()); // false

4.是否含特定key   map.containsKey():

HashMap<Integer, String> map = new HashMap<>();
//判断map中是否存在这个key
System.out.println((map.containsKey(1)); // false
map.put(1, "Sheldon");
System.out.println((map.containsKey(1)); // true

5.是否包含特定value   map.containsValue():

HashMap<Integer, String> map = new HashMap<>();
//判断map中是否存在这个value
map.containsValue("Missy"); // false
map.put(1, "Missy");
map.containsValue("Missy"); // true

6.获取所有的value   map.values()

HashMap<Integer, String> map = new HashMap<>();
//显示所有的value值
System.out.println(map.values()); // []
map.put(3, "Gugu");
map.put(8, "fenda");
System.out.println(map.values()); // ["Gugu", "fenda"]

7.获取所有的key  map.keySet()

HashMap<Integer, String> map = new HashMap<>();
//显示所有的value值
System.out.println(map.keySet(); // []
map.put(3, "Gugu");
map.put(8, "fenda");
System.out.println(map.keySet()); // [3, 8]

8.元素个数 map.size():

HashMap<Integer, String> map = new HashMap<>();
map.put(3, "Gugu");
map.put(8, "fenda");
//获取map里元素的数量
int i = map.size(); // 2

9.删除这个key和value:

HashMap<String, Integer> map=new HashMap<>();
/*boolean*///删除这个键值对
map.put("DEMO1", 1);
map.put("DEMO2", 2);
System.out.println(map);//{DEMO1=1, DEMO2=2}
System.out.println(map.remove("DEMO2", 1));//false
System.out.println(map.remove("DEMO2", 2));//true
System.out.println(map);//{DEMO1=1}

原文链接:https://www.cnblogs.com/jiuhaoyun/p/8985643.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值