Map集合中的常用函数:put、get、remove、containsKey、isEmpty
Map集合是一种数据结构,用于存储键-值对。在Java中,Map是一个接口,它的实现类包括HashMap、TreeMap以及LinkedHashMap等。Map集合中的常用函数包括put、get、remove、containsKey、isEmpty等。本文将依次对这些函数进行介绍。
1. put函数
put函数用于向Map集合中添加键-值对。它的语法为:
V put(K key, V value)
其中,key表示要添加的键,value表示要添加的值。put函数将键-值对添加到Map集合中,并返回对应的值。如果原先存在该键,则会将值覆盖。示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("grape", 3);
System.out.println(map); //{grape=3, apple=1, banana=2}
2. get函数
get函数用于从Map集合中获取键对应的值。它的语法为:
V get(Object key)
其中,key表示要获取值的键。get函数返回键对应的值,如果该键不存在,则返回null。示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("grape", 3);
System.out.println(map.get("apple")); //1
3. remove函数
remove函数用于从Map集合中移除指定的键及其对应的值。它的语法为:
V remove(Object key)
其中,key表示要移除的键。remove函数返回被移除的键对应的值,如果该键不存在,则返回null。示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("grape", 3);
Integer value = map.remove("banana");
System.out.println(value); //2
System.out.println(map); //{grape=3, apple=1}
4. containsKey函数
containsKey函数用于判断Map集合中是否存在指定的键。它的语法为:
boolean containsKey(Object key)
其中,key表示要查找的键。containsKey函数返回true,如果Map集合中存在该键;返回false,如果Map集合中不存在该键。示例代码如下:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("grape", 3);
System.out.println(map.containsKey("apple")); //true
System.out.println(map.containsKey("coconut")); //false
5. isEmpty函数
isEmpty函数用于判断Map集合是否为空。它的语法为:
boolean isEmpty()
isEmpty函数返回true,如果Map集合为空;返回false,如果Map集合不为空。示例代码如下:
Map<String, Integer> map = new HashMap<>();
System.out.println(map.isEmpty()); //true
map.put("apple", 1);
System.out.println(map.isEmpty()); //false
总结:
在使用Map集合时,常用的函数包括put、get、remove、containsKey、isEmpty等。它们可以帮助我们向Map集合中添加键-值对、获取键对应的值、移除指定的键以及判断Map集合中是否存在指定的键或者是否为空。掌握这些函数,可以帮助我们更加高效地使用Map集合。
