import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// 创建一个HashMap实例
Map<String, Integer> map = new HashMap<>();
// put: 向Map中添加键值对
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// get: 根据键获取对应的值
System.out.println("Value for 'apple': " + map.get("apple")); // 输出: Value for 'apple': 1
// containsKey: 检查Map中是否包含指定的键
System.out.println("Contains 'banana': " + map.containsKey("banana")); // 输出: Contains 'banana': true
// containsValue: 检查Map中是否包含指定的值
System.out.println("Contains value '3': " + map.containsValue(3)); // 输出: Contains value '3': true
// size: 获取Map中的键值对数量
System.out.println("Size of map: " + map.size()); // 输出: Size of map: 3
// remove: 根据键移除键值对
map.remove("orange");
System.out.println("After removing 'orange', size of map: " + map.size()); // 输出: After removing 'orange', size of map: 2
// clear: 清空Map中的所有键值对
map.clear();
System.out.println("After clearing, size of map: " + map.size()); // 输出: After clearing, size of map: 0
// putIfAbsent: 如果Map中不存在该键,则添加键值对
map.putIfAbsent("grape", 4);
System.out.println("Value for 'grape': " + map.get("grape")); // 输出: Value for 'grape': 4
// replace: 替换指定键的值
map.put("grape", 4);
map.replace("grape", 5);
System.out.println("After replacing, value for 'grape': " + map.get("grape")); // 输出: After replacing, value for 'grape': 5
// keySet: 获取Map中所有的键,返回一个Set集合
map.put("apple", 1);
map.put("banana", 2);
System.out.println("Keys in map: " + map.keySet()); // 输出: Keys in map: [apple, banana]
// values: 获取Map中所有的值,返回一个Collection集合
System.out.println("Values in map: " + map.values()); // 输出: Values in map: [1, 2]
// entrySet: 获取Map中所有的键值对,返回一个Set集合,每个元素是一个Map.Entry对象
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 输出:
// Key: apple, Value: 1
// Key: banana, Value: 2
}
}
new HashMap<>()
创建一个HashMap
实例。Set
集合。Collection
集合。Set
集合,每个元素是一个Map.Entry
对象。Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站