HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。根据键的 HashCode 值存储数据,具有很快的访问速度,最多允许一条记录的键为 null,不支持线程同步。HashMap 是无序的,即不会记录插入的顺序。HashMap 继承于AbstractMap,实现了 Map、Cloneable、java.io.Serializable 接口。
WV9wXLl-2.pngHashMap 的 key 与 value 类型可以相同也可以不同,可以是字符串(String)类型的 key 和 value,也可以是整型(Integer)的 key 和字符串(String)类型的 value。
截屏2023-04-09 16.05.37.pngHashMap 类位于 java.util 包中,使用前需要引入它。HashMap 中的元素实际上是对象,一些常见的基本类型可以使用它的包装类。
添加元素:添加键值对(key-value)可以使用 put() 方法。
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites);
}
}
// 执行以上代码,输出结果如下:
// {1=Google, 2=Runoob, 3=Taobao, 4=Zhihu}
访问元素:使用 get(key) 方法来获取 key 对应的 value。
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites.get(3));
}
}
// 执行以上代码,输出结果如下:
// Taobao
删除元素:使用 remove(key) 方法来删除 key 对应的键值对(key-value)。
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
Sites.remove(4);
System.out.println(Sites);
}
}
// 执行以上代码,输出结果如下:
// {1=Google, 2=Runoob, 3=Taobao}
删除所有键值对(key-value):可以使用 clear 方法:
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
Sites.clear();
System.out.println(Sites);
}
}
// 执行以上代码,输出结果如下:
// {}
计算大小:计算 HashMap 中的元素数量可以使用 size() 方法。
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
System.out.println(Sites.size());
}
}
// 执行以上代码,输出结果如下:
// 4
迭代 HashMap
可以使用 for-each 来迭代 HashMap 中的元素。如果你只想获取 key,可以使用 keySet() 方法,然后可以通过 get(key) 获取对应的 value,如果你只想获取 value,可以使用 values() 方法。
// 引入 HashMap 类
import java.util.HashMap;
public class RunoobTest {
public static void main(String[] args) {
// 创建 HashMap 对象 Sites
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
// 输出 key 和 value
for (Integer i : Sites.keySet()) {
System.out.println("key: " + i + " value: " + Sites.get(i));
}
// 返回所有 value 值
for(String value: Sites.values()) {
// 输出每一个value
System.out.print(value + ", ");
}
}
}
// 执行以上代码,输出结果如下:
// key: 1 value: Google
// key: 2 value: Runoob
// key: 3 value: Taobao
// key: 4 value: Zhihu
// Google, Runoob, Taobao, Zhihu,
HashMap 常用方法列表如下:
方法 | 描述 |
---|---|
clear() | 删除 hashMap 中的所有键/值对 |
clone() | 复制一份 hashMap |
isEmpty() | 判断 hashMap 是否为空 |
size() | 计算 hashMap 中键/值对的数量 |
put() | 将键/值对添加到 hashMap 中 |
putAll() | 将所有键/值对添加到 hashMap 中 |
putIfAbsent() | 如果 hashMap 中不存在指定的键,则将指定的键/值对插入到 hashMap 中 |
remove() | 删除 hashMap 中指定键 key 的映射关系 |
containsKey() | 检查 hashMap 中是否存在指定的 key 对应的映射关系 |
containsValue() | 检查 hashMap 中是否存在指定的 value 对应的映射关系 |
replace() | 替换 hashMap 中是指定的 key 对应的 value |
replaceAll() | 将 hashMap 中的所有映射关系替换成给定的函数所执行的结果 |
get() | 获取指定 key 对应对 value |
getOrDefault() | 获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值 |
forEach() | 对 hashMap 中的每个映射执行指定的操作 |
entrySet() | 返回 hashMap 中所有映射项的集合集合视图 |
keySet() | 返回 hashMap 中所有 key 组成的集合视图 |
values() | 返回 hashMap 中存在的所有 value 值 |
merge() | 添加键值对到 hashMap 中 |
compute() | 对 hashMap 中指定 key 的值进行重新计算 |
computeIfAbsent() | 对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hasMap 中 |
computeIfPresent() | 对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中 |
HashMap的工作原理
- HashMap内部利用数组存储数据。
- 根据Key的 hashCode 值计算出数组的下标位置,进行添加或者查询数据。根据 hashCode 计算出数组的下标位置的算法称为”散列算法“。
- 数组的下标位置会重复,重复的时候利用链表存储重复元素,这个链表称为”散列桶“。
- 添加和查询的时候如果有”散列桶“,则根据 equals 方法逐个比较找到位置。
由于利用 hashCode 直接定位到数组的存储位置,无需依次查找,所以 HashMap 具有极高的查找性能。
影响 HashMap 查找性能的因素
- 如果数据多,而数组容量少,大量数据重复的存储在”散列桶“中,造成在”散列桶“中进行大量的顺序查找,性能差。
解决办法:提供更多数组容量,减少”散列桶“中重复的数据,如果保持元素的总数和数组容量的比例少于 75% 的时候,出现重复位置少于3个。HashMap 中默认的“加载因子”就是 75%,HashMap 中添加元素的时候,HashMap 始终会保持元素和数组容量的比例小于 75%,超过 75% 则进行数组扩容以“重新散列”。
- 如果数据多,而数组容量少,大量数据重复的存储在”散列桶“中,造成在”散列桶“中进行大量的顺序查找,性能差。
- hashCode 方法,在Java的Object类上定义了 hashCode 方法,用于支持HashMap 中的算法。作为Key的类型必须很好的实现 hashCode 方法,否则会影响 HashMap 的性能。
- equals 方法,HashMap添加或查找的时候,先根据 hashCode 计算数组下标位置,然后再利用 equals 方法比较 Key 对象是否相同。如果 Key 的 hashCode 和 equals 方法不“一致”,会造成 HashMap 工作异常!可能重复添加或查找不到数据。
- 创建 HashMap 的性能优化参数,采用 new HashMap(数组容量,加载因子)的方式创建 HashMap。默认new HashMap() 方式等价于 new HashMap(16,0.75f),如果事先可以预测到添加到 HashMap 中的键值映射(key - value)的数量,则可以声明足够大的容量,避免反复扩容浪费时间。
clear() 方法:
public void clear()
描述:
用于删除指定 hashMap 中所有键/值对。
参数:
无
返回值:
无
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> sites = new HashMap<>();
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// 从HashMap中删除所有映射
sites.clear();
System.out.println("使用 clear() 方法后: " + sites);
}
}
// 以上程序执行结果为:
// HashMap: {1=Google, 2=JueJin, 3=Taobao}
// 使用 clear() 方法后: {}
clone() 方法:
public Object clone()
描述:
用于复制一份 hashMap,属于浅拷贝。
参数:
无
返回值:
返回HashMap实例(对象)的副本。
public class Test {
public static void main(String args[]) {
HashMap<Integer, String> sites = new HashMap<>();
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// 复制 sites
HashMap<Integer, String> cloneSites = (HashMap<Integer, String>)sites.clone();
System.out.println("Cloned HashMap: " + cloneSites);
}
}
// 以上程序执行结果为:
// HashMap: {1=Google, 2=JueJin, 3=Taobao}
// Cloned HashMap: {1=Google, 2=JueJin, 3=Taobao}
isEmpty() 方法:
public boolean isEmpty()
描述:
用于检查该 HashMap 是否为空。
参数:
无
返回值:
如果 HashMap 中不包含任何键/值对的映射关系则返回 true,否则返回 false。
public class Test {
public static void main(String args[]) {
HashMap<Integer, String> sites = new HashMap<>();
// 检查该 HashMap 是否含有元素
boolean result = sites.isEmpty(); // true
System.out.println("是否为空? " + result);
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
result = sites.isEmpty(); // false
System.out.println("是否为空? " + result);
}
}
// 以上程序执行结果为:
// 是否为空? true
// HashMap: {1=Google, 2=JueJin, 3=Taobao}
// 是否为空? false
size() 方法:
public int size()
描述:
用于计算 hashMap 中键/值对的数量。
参数:
无
返回值:
返回 hashMap 中键/值对的数量。
public class Test {
public static void main(String args[]) {
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// 获得该 HashMap 中键/值对映射的数量
int size = sites.size();
System.out.println("Size of HashMap: " + size);
}
}
// 以上程序执行结果为:
// HashMap: {1=Google, 2=JueJin, 3=Taobao}
// Size of HashMap: 3
put() 方法:
public V put(K key, V value)
描述:
将指定的键/值对插入到 HashMap 中。
参数:
- key -- 键。
- value -- 值。
返回值:
如果插入的 key 对应的 value 已经存在,则执行 value 替换操作,返回旧的 value 值,如果不存在则执行插入,返回 null。
public class Test {
public static void main(String args[]) {
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
}
}
// 以上程序执行结果为:
// HashMap: {1=Google, 2=JueJin, 3=Taobao}
putAll() 方法:
public void putAll(Map<? extends K, ? extends V> m)
描述:
将指定所有的键/值对插入到 HashMap 中。
参数:
- m -- 包含插入到 HashMap 的映射关系。
返回值:
无
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 创建另一个 HashMap
HashMap<Integer, String> sites2 = new HashMap<>();
sites2.put(1, "Weibo"); // 已存在会被替换
sites2.put(4, "JueJin");
// 将所有的映射关系从 sites 添加到 sites2
sites2.putAll(sites);
System.out.println("sites2 HashMap: " + sites2);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// sites2 HashMap: {1=Google, 2=Runoob, 3=Taobao, 4=JueJin}
putIfAbsent() 方法:
public V putIfAbsent(K key, V value)
描述:
先判断指定的键(key)是否存在,不存在则将键/值对插入到 HashMap 中。
参数:
- key -- 键。
- value -- 值。
返回值:
如果所指定的 key 已经在 HashMap 中存在,返回和这个 key 值对应的 value, 如果所指定的 key 不在 HashMap 中存在,则返回 null。
注意:
如果指定 key 之前已经和一个 null 值相关联了 ,则该方法也返回 null。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// HashMap 不存在该key
sites.putIfAbsent(4, "JueJin");
// HashMap 中存在 Key
sites.putIfAbsent(2, "Wiki");
System.out.println("Updated Languages: " + sites);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// Updated Languages: {1=Google, 2=Runoob, 3=Taobao, 4=JueJin}
remove() 方法:
// 该方法有以下几种语法格式:
public V remove(Object key)
public boolean remove(Object key, Object value)
描述:
用于删除hashMap 中指定键 key 对应的键值对(key-value)。
参数:
- key -- 键值。
- value -- (可选)键值对(key-value)中 key 对应的 value 值。
返回值:
如果指定 key,返回指定键 key 关联的值,如果指定的 key 映射值为 null 或者该 key 并不存在于该 HashMap 中,此方法将返回null。
如果同时指定了 key 和 value,删除成功返回 true,否则返回 false。
public class Test {
public static void main(String args[]) {
HashMap<Integer, String> sites = new HashMap<>();
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("HashMap: " + sites);
// 删除key为2的映射关系
String siteName = sites.remove(2); // return Runoob
System.out.println("返回值: " + siteName);
System.out.println("删除后的 HashMap: " + sites);
// 删除key为2的映射关系
Boolean flag1 = sites.remove(1, "Google"); // return true
Boolean flag2 = sites.remove(3, "Weibo"); // return false
System.out.println("返回值 flag1: " + flag1);
System.out.println("返回值 flag2: " + flag2);
System.out.println("删除后的 HashMap: " + sites);
}
}
// 以上程序执行结果为:
// HashMap: {1=Google, 2=Runoob, 3=Taobao}
// 返回值: Runoob
// 删除后的 HashMap: {1=Google, 3=Taobao}
// 返回值 flag1: true
// 返回值 flag2: false
// 删除后的 HashMap: {3=Taobao}
containsKey() 方法:
public boolean containsKey(Object key)
描述:
检查 hashMap 中是否存在指定的 key 对应的映射关系。
参数:
- key -- 键。
返回值:
如果 hashMap 中存在指定的 key 对应的映射关系返回 true,否则返回 false。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
//检查 key 为 1 是否存在
if(sites.containsKey(1)) {
System.out.println("key 为 1 存在于 sites 中");
}
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// key 为 1 存在于 sites 中
containsValue() 方法:
public boolean containsValue(Object value)
描述:
检查 hashMap 中是否存在指定的 value 对应的映射关系。
参数:
- value -- 值。
返回值:
如果 hashMap 中是否存在指定的 value 对应的映射关系返回 true,否则返回 false。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
//检查映射中值value是否有Java
if(sites.containsValue("JueJin")) {
System.out.println("JueJin 存在于 sites 中");
}
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=JueJin, 3=Taobao}
// JueJin 存在于 sites 中
replace() 方法:
// 该方法有以下几种语法格式:
public V replace(K key, V value)
public boolean replace(K key, V oldValue, V newValue)
描述:
替换 hashMap 中是指定的 key 对应的 value。
参数:
- key -- 键。
- oldValue -- 旧的 value 值。
- newValue -- 新的 value 值。
返回值:
如果 oldValue 不存在,则替换 key 对应的值,返回 key 对应的旧值。如果 key 不存在,则返回 null。
如果存在 oldValue,替换成功返回 true,否则返回 false。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 替换key为2的映射
String value = sites.replace(2, "Wiki");
System.out.println("Replaced Value: " + value);
System.out.println("Updated HashMap: " + sites);
// 替换映射关系{1 = Google},执行替换
sites.replace(1, "Google", "Wiki"); // 返回 true
// 不存在映射关系{2 = Weibo},没有任何操作
sites.replace(2, "Weibo", "Zhihu"); // 返回 false
System.out.println("sites after replace():\n" + sites);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=JueJin, 3=Taobao}
// Replaced Value: JueJin
// Updated HashMap: {1=Google, 2=Wiki, 3=Taobao}
// sites after replace():
// {1=Wiki, 2=Wiki, 3=Taobao}
replaceAll() 方法:
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)
描述:
将 hashMap 中的所有映射关系替换成给定的函数所执行的结果。
参数:
- function -- 执行对函数。
返回值:
不返回任何值,仅替换了 HashMap 中的所有值。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "JueJin");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 将所有的值更改为大写
sites.replaceAll((key, value) -> value.toUpperCase());
System.out.println("Updated HashMap: " + sites);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=JueJin, 3=Taobao}
// Updated HashMap: {1=GOOGLE, 2=JUEJIN, 3=TAOBAO}
get() 方法:
public V get(Object key)
描述:
获取指定 key 对应对 value。
参数:
- key -- 键。
返回值:
回与指定 key 所关联的 value。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 得到 value
String value = sites.get(1);
System.out.println("key 1 对应的 value: " + value);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// key 1 对应的 value: Google
getOrDefault() 方法:
public V getOrDefault(Object key, V defaultValue)
描述:
获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。
参数:
- key -- 键。
- defaultValue -- 当指定的key并不存在映射关系中,则返回的该默认值。
返回值:
返回 key 相映射的的 value,如果给定的 key 在映射关系中找不到,则返回指定的默认值。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// key 的映射存在于 HashMap 中
// Not Found - 如果 HashMap 中没有该 key,则返回默认值
String value1 = sites.getOrDefault(1, "Not Found");
System.out.println("Value for key 1: " + value1);
// key 的映射不存在于 HashMap 中
// Not Found - 如果 HashMap 中没有该 key,则返回默认值
String value2 = sites.getOrDefault(4, "Not Found");
System.out.println("Value for key 4: " + value2);
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// Value for key 1: Google
// Value for key 4: Not Found
forEach() 方法:
public void forEach(BiConsumer<? super K, ? super V> action)
描述:
用于对 HashMap 中的每个映射执行指定的操作。
参数:
- action -- 要执行的操作。
返回值:
无
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往 HashMap 中插入映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("Normal Price: " + prices);
System.out.print("Discounted Price: ");
//通过 lambda 表达式使用 forEach()
prices.forEach((key, value) -> {
// value 价格减少百分之 10
value = value - value * 10/100;
System.out.print(key + "=" + value + " ");
});
}
}
// 以上程序执行结果为:
// Normal Price: {Pant=150, Bag=300, Shoes=200}
// Discounted Price: Pant=135 Bag=270 Shoes=180
entrySet() 方法:
public Set<Map.Entry<K,V>> entrySet()
描述:
返回映射中包含的映射的 Set 视图。
参数:
无
返回值:
返回此映射中包含的映射的 Set 视图。
注意:
Set 视图意思是 HashMap 中所有的键值对都被看作是一个 set 集合。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 返回映射关系中 set view
System.out.println("Set View: " + sites.entrySet());
// entrySet()返回了 HashMap 中所有映射项的一个 set 集合视图
// for-each loop 在该视图中访问了每一映射项
System.out.println();
System.out.println("entrySet() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中每一个映射项: ");
for(Map.Entry<Integer,String> entry: sites.entrySet()) {
System.out.print(entry);
System.out.print(", ");
}
}
}
// 上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// Set View: [1=Google, 2=Runoob, 3=Taobao]
// entrySet() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中每一个映射项:
// 1=Google, 2=Runoob, 3=Taobao,
keySet() 方法:
public Set<K> keySet()
描述:
返回映射中所有 key 组成的 Set 视图。
参数:
无
返回值:
返回映射中所有 key 组成的 Set 视图。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 返回所有 key 组成的 set 集合视图
System.out.println("Keys: " + sites.keySet());
// keySet() 返回所有 key 组成的 set 视图
// for-each loop 在该视图中访问每一个 key
System.out.println();
System.out.println("keySet() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中的所有键:");
for(int key: sites.keySet()) {
// 输出每个 key
System.out.print(key + ", ");
}
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// Keys: [1, 2, 3]
// keySet() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中的所有键:
// 1, 2, 3,
values() 方法:
public Collection<V> values()
描述:
返回映射中所有 value 组成的 Set 视图。
参数:
无
返回值:
返回 HashMap 中所有 value 值所组成的 collection view(集合视图)。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<Integer, String> sites = new HashMap<>();
// 往 HashMap 添加一些元素
sites.put(1, "Google");
sites.put(2, "Runoob");
sites.put(3, "Taobao");
System.out.println("sites HashMap: " + sites);
// 返回所有value值组成的视图
System.out.println("Values: " + sites.values());
// values() 返回所有 value 的一个视图
// for-each 循环可以 从view中访问每一个value值
System.out.println();
System.out.println("values() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中的所有值:");
for(String value: sites.values()) {
// 输出每一个value
System.out.print(value + ", ");
}
}
}
// 以上程序执行结果为:
// sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
// Values: [Google, Runoob, Taobao]
// values() 方法可以与 for-each 循环一起使用,用来遍历迭代 HashMap 中的所有值:
// Google, Runoob, Taobao,
merge() 方法:
public V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction)
描述:
判断指定的 key 是否存在,如果不存在,则添加键值对到 hashMap 中。
参数:
- key -- 键。
- value -- 值。
- remappingFunction -- 重新映射函数,用于重新计算值。
返回值:
如果 key 对应的 value 不存在,则返回该 value 值,如果存在,则返回通过 remappingFunction 重新计算后的值。
public class Test {
public static void main(String args[]) {
//创建一个HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往 HashMap 插入映射
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
System.out.println("指定的Key不存在时:");
// 因为键 Shirt 并不在 prices 中,merge() 方法将映射 Shirt=100 插入到 prices,重新映射函数的执行结果被忽略。
int returnedValue = prices.merge("Shirt", 100, (oldValue, newValue) -> oldValue + newValue);
System.out.println("Price of Shirt: " + returnedValue);
// 输出更新后的 HashMap
System.out.println("Updated HashMap: " + prices);
System.out.println("指定的Key已经存在时:");
// 因为键 Shoes 已经存在于 prices,旧值被重映射函数返回的值替换。因此,Shoes 的映射值更改为280。
int returnedValue2 = prices.merge("Shoes", 80, (oldValue, newValue) -> oldValue + newValue);
System.out.println("Price of Shoes: " + returnedValue2);
//输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
}
}
// 以上程序执行结果为:
// HashMap: {Pant=150, Bag=300, Shoes=200}
// 指定的Key不存在时:
// Price of Shirt: 100
// Updated HashMap: {Pant=150, Shirt=100, Bag=300, Shoes=200}
// 指定的Key已经存在时:
// Price of Shoes: 280
// Updated HashMap: {Pant=150, Shirt=100, Bag=300, Shoes=280}
compute() 方法:
public V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
描述:
对 hashMap 中指定 key 的值进行重新计算。
参数:
- key -- 键。
- remappingFunction -- 重新映射函数,用于重新计算值。
返回值:
如果 key 对应的 value 不存在,则返回 null,如果存在,则返回通过 remappingFunction 重新计算后的值。
public class Test {
public static void main(String args[]) {
//创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// 重新计算鞋子打了10%折扣后的值
int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
System.out.println("Discounted Price of Shoes: " + newPrice);
// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
}
}
// 以上程序执行结果为:
// HashMap: {Pant=150, Bag=300, Shoes=200}
// Discounted Price of Shoes: 180
// Updated HashMap: {Pant=150, Bag=300, Shoes=180}
computeIfAbsent() 方法:
public V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction)
描述:
对 hashMap 中指定 key 的值进行重新计算,如果不存在这个 key,则添加到 hashMap 中。
参数:
- key -- 键。
- remappingFunction -- 重新映射函数,用于重新计算值。
返回值:
如果 key 对应的 value 不存在,则使用获取 remappingFunction 重新计算后的值,并保存为该 key 的 value,否则返回 value。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射项
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// 计算 Shirt 的值
System.out.println("指定的Key不存在时:");
int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
System.out.println("Price of Shirt: " + shirtPrice);
// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
// Shoes中的映射关系已经存在
// Shoes并没有计算新值
System.out.println("指定的Key已经存在时:");
int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
System.out.println("Price of Shoes: " + shoePrice);
// 输出更新后的 HashMap
System.out.println("Updated HashMap: " + prices);
}
}
// 以上程序执行结果为:
// HashMap: {Pant=150, Bag=300, Shoes=200}
// 指定的Key不存在时:
// Price of Shirt: 280
// Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
// 指定的Key已经存在时:
// Price of Shoes: 200
// Updated HashMap: {Pant=150, Shirt=280, Bag=300, Shoes=200}
computeIfPresent() 方法:
public V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
描述:
对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。
参数:
- key -- 键。
- remappingFunction -- 重新映射函数,用于重新计算值。
返回值:
如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。
public class Test {
public static void main(String args[]) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射关系
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// 重新计算鞋加上10%的增值税后的价值
int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
System.out.println("Price of Shoes after VAT: " + shoesPrice);
// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
}
}
// 以上程序执行结果为:
// HashMap: {Pant=150, Bag=300, Shoes=200}
// Price of Shoes after VAT: 220
// Updated HashMap: {Pant=150, Bag=300, Shoes=220}
网友评论