java map的常用方法吗_Java Map的常用方法

1.V put(K key, V value)

向map集合中添加Key为key,Value为value的元素,当添加成功时返回null,否则返回value。

就是说Map集合中的Key是不能重复的,但是Map集合中的Value是可以重复。

Map map = new HashMap<>();

map.put(1,1);

2.void putAll(Map extends K,? extends V> m)

向map集合中添加指定集合的所有元素

Map map = new HashMap<>();

map.put(1, 1);

map.put(2, 1);

map.put(3, 1);

Map map2 = new HashMap<>();

map2.putAll(map);//深拷贝

Map map3 = new HashMap<>(map);//map2等同于map3

map.put(4, 1);

map.put(1, 2);

结果:

20200326162541753259.png

3.void clear()

把map集合中所有的键值删除

map.clear();

4.boolean containsKey(Object key)

检出map集合中有没有包含Key为key的元素,如果有则返回true,否则返回false。

Map map = new HashMap<>();

map.put(1, 1);

map.put(2, 1);

boolean a = map.containsKey(1);

boolean b = map.containsKey(3);

结果:

20200326162542782490.png

5.boolean containsValue(Object value)

检出map集合中有没有包含Value为value的元素,如果有则返回true,否则返回false。

Map map = new HashMap<>();

map.put(1, 1);

map.put(2, 1);

boolean a = map.containsValue(1);

boolean b = map.containsValue(2);

结果:

20200326162542782490.png

6.Set> entrySet()

返回map到一个Set集合中,以map集合中的Key=Value的形式返回到set中。

Map map = new HashMap<>();

map.put(1, 1);

map.put(2, 1);

Set> set = map.entrySet();

//遍历map的方法

for (Map.Entry m : map.entrySet()) {

System.out.print("key:" + m.getKey() + "\n" + "value:" + m.getValue() + "\n");

}

/*

输出:key:1

value:1

key:2

value:1

*/

7.boolean equals(Object o)

判断两个map集合的元素是否相同

Map map = new HashMap<>();

map.put(1, 1);

map.put(2, 1);

Map map2 = new HashMap<>(map);

System.out.print(map.equals(map2));

//输出true

8.V get(Object key)

根据map集合中元素的Key来获取相应元素的Value

Map map = new HashMap<>();

map.put(1, 3);

map.put(2, 4);

int value = map.get(1);

System.out.print(value);//输出3

9.boolean isEmpty()

检出map集合中是否有元素,如果没有则返回true,如果有元素则返回false

Map map = new HashMap<>();

boolean a1 = map.isEmpty();//true

map.put(1, 3);

map.put(2, 4);

boolean a2 = map.isEmpty();//false

10.SetkeySet()

返回map集合中所有Key

Map map = new HashMap<>();

map.put(1, 3);

map.put(2, 4);

Set set = map.keySet();

for (Integer i : set) {

System.out.print(i);//输出12

}

11.V remove(Object key)

删除Key为key值的元素

Map map = new HashMap<>();

map.put(1, 3);

map.put(2, 4);

System.out.print("删除前:" + map);

map.remove(1);

System.out.print("删除后:" + map);

//输出:删除前:{1=3, 2=4} 删除后:{2=4}

12.int size()

返回map集合中元素个数

Map map = new HashMap<>();

map.put(1, 3);

map.put(2, 4);

int size = map.size();

System.out.print(size);//输出2

13.Collectionvalues()

返回map集合中所有的Value到一个Collection集合

Map map = new HashMap<>();

map.put(1, 3);

map.put(2, 4);

Collection c = map.values();

System.out.print(c);//输出:[3, 4]

原文:https://www.cnblogs.com/xym4869/p/12574277.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值