Map
Map 中的数据是以键值对 key-value 的形式存储的,通过key 找到value, key不能重复
Java中有两种常用的Map。一种是 HashMap 键值无序。另一种是TreeMap, 键值有序。
本节完整代码可以访问 我的github仓库
Map的创建
HashMap 和 TreeMap的创建
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new TreeMap<>();
Map 的增, 删, 改, 查
增和改都可以通过put()方法实现, 删除操作可用remove()实现, 查操作可用 contains()实现
map1.put("Pig", "猪");
map1.put("Dog", "狗");
map1.put("Cat", "猫");
map1.put("elephant", "象");
map1.remove("elephant");
if (map1.containsKey("Pig")){
System.out.println("Pig 中文意思是 "+ map1.get("Pig"));
}
Map的遍历
通过entrySet()方法获得 键值对
// 打印输出Map的key和value,通过entrySet方法
// entrySet返回值是Set<Entry<key类型, value类型>>
System.out.println("通过entrySet得到key-value :");
Set<Entry<String, String>> entrySet = map1.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey() + " - ");
System.out.println(entry.getValue());
}
通过 keySet() 方法获得 key 的集合, 再通过key 去访问 value
// 打印输出Map的key和value,通过keySet方法
System.out.println("通过keySet得到key-value :");
// 1.取得KeySet
Set<String> keySet = map1.keySet();
// 2.遍历keySet
for (String key : keySet) {
System.out.println( key + " - " + map1.get(key));
}
使用迭代器遍历 Map 的 values (嫌语法麻烦的可以不用这种方法hhh)
// 打印输出Map的values, 使用迭代器
System.out.println("打印输出Map的values, 使用迭代器 ");
Iterator<String> it = map1.values().iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
使用增强型 for 循环遍历 Map 的 values
System.out.println("打印输出Map的values, 使用迭代器 ");
for (String s: map1.values()) {
System.out.println(s);
}
TreeMap 也支持以上的所有方法, 区别是 TreeSet 会对所有 key 的顺序 进行动态维护
Last updated
Was this helpful?