1.创建Map对象
Map<KeyType, ValueType> map = new HashMap<>();
2.添加元素
map.put(key, value);
3.获取元素
普通方式
ValueType value = map.get(key);
尝试获取,没有则返回给定的默认值
ValueType value = map.getOrDefault(key, defaultValue);
4.修改元素
map.put(key, newValue)
《!技巧写法》
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("key1", 10);
map.put("key2", 20);
// 修改指定键的值,如果键不存在,则添加键值对
map.put("key3", map.getOrDefault("key3", 0) + 30);
System.out.println(map); // 输出:{key1=10, key2=20, key3=30}
5.删除指定元素
map.remove(key);
6.删除所有元素
map.clear();
7.检查是否包含指定的键
boolean containsKey = map.containsKey(key);
8.获取Map的键值对对象
Set<Map.Entry<KeyType, ValueType>> entrySet = map.entrySet();
9.获取Map的所有键
Set<KeyType> keySet = map.keySet();
10.获取Map的所有值
Collection<ValueType> values = map.values();
获取Map的所有值并转化为ArrayList储存
ArrayList<String> valuesList = new ArrayList<>(map.values());
11.遍历键值对集合
for (Map.Entry<KeyType, ValueType> entry: map.entrySet()){
KeyType key = entry.getKey();
ValueType value = entry.getValue();
}
12.判断两个Map的键值对是否完全相同
public static <K, V> boolean mapsEqual(Map<K, V> map1, Map<K, V> map2) {
// Step 1: Check if sizes are equal
if (map1.size() != map2.size()) {
return false;
}
// Step 2: Check if each key-value pair in map1 exists in map2
for (Map.Entry<K, V> entry: map1.entrySet()){
K key = entry.getKey();
V value = entry.getValue();
if (!map2.containsKey(key) || !Objects.equals(map2.get(key), value)) {
return false;
}
}
// All key-value pairs are equal
return true;
}
13.从Map中随机选择一个键
// 从Map中随机选择一个键的方法
public static <K, V> K getRandomKey(Map<K, V> map) {
// 获取Map中所有的键集合
Set<K> keySet = map.keySet();
// 创建一个随机数生成器
Random random = new Random();
// 生成一个随机索引,范围在键集合的大小之间
int randomIndex = random.nextInt(keySet.size());
// 获取随机索引位置的键
K[] keys = keySet.toArray((K[]) new Object[keySet.size()]);
return keys[randomIndex];
}
14.Map以值的大小为概率随机选择键
import java.util.*;
public class RandomKeyFromMap {
public static void main(String[] args) {
// 创建一个Map并添加键值对
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
// 从Map中按值的大小为概率随机选择一个键
String randomKey = getRandomKey(map);
System.out.println("Randomly selected key: " + randomKey);
}
public static <K> K getRandomKey(Map<K, Integer> map) {
// 计算Map中所有值的总和
int total = map.values().stream().mapToInt(Integer::intValue).sum();
// 生成一个随机数,范围在0到总和之间
Random random = new Random();
int randomNumber = random.nextInt(total);
// 遍历Map中的键值对,并累积值,直到累积值超过随机数
int cumulativeSum = 0;
for (Map.Entry<K, Integer> entry : map.entrySet()) {
cumulativeSum += entry.getValue();
if (randomNumber <= cumulativeSum) {
return entry.getKey();
}
}
// 如果出现异常情况(例如Map为空),返回null
return null;
}
}