import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// 创建一个HashMap实例
Map<String, Integer> map = new HashMap<>();
// 向Map中添加键值对
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 获取指定键的值
System.out.println("Value for key 'Apple': " + map.get("Apple"));
// 检查Map中是否包含某个键
if (map.containsKey("Banana")) {
System.out.println("Map contains key 'Banana'");
}
// 遍历Map中的所有键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 删除指定键的条目
map.remove("Orange");
// 打印删除后的Map大小
System.out.println("Size of the map after removing 'Orange': " + map.size());
}
}
HashMap类创建一个名为map的实例。put方法向map中添加键值对。get方法根据键获取对应的值。containsKey方法检查某个键是否存在于map中。entrySet方法遍历map中的所有键值对。remove方法删除指定键的条目。size方法获取map的大小。上一篇:java map按照key排序
下一篇:java date减一天
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站