java中Map集合的遍历操作
1. Map 集合的基本操作
1.1 Map集合概述和特点
- A:Map接口概述
- 查看API可以知道:
- 将键映射到值的对象
- 一个映射不能包含重复的键
- 每个键最多只能映射到一个值
- B:Map接口和Collection接口的不同
- Map是双列的,Collection是单列的
- Map的键唯一,Collection的子体系Set是唯一的
- Map集合的数据结构值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
1.2 Map集合的功能概述
- A:Map集合的功能概述
- a:添加功能
- V put(K key,V value):添加元素。
- 如果键是第一次存储,就直接存储元素,返回null
- 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值
- b:删除功能
- void clear():移除所有的键值对元素
- V remove(Object key):根据键删除键值对元素,并把值返回
- c:判断功能
- boolean containsKey(Object key):判断集合是否包含指定的键
- boolean containsValue(Object value):判断集合是否包含指定的值
- boolean isEmpty():判断集合是否为空
- d:获取功能
- Set<Map.Entry<K,V>> entrySet():
- V get(Object key):根据键获取值
- Set keySet():获取集合中所有键的集合
- Collection values():获取集合中所有值的集合
- e:长度功能
public class Demo1_Map {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("张三", 23);
map.put("李四", 24);
map.put("王五", 25);
map.put("赵六", 26);
Collection<Integer> c = map.values();
System.out.println(c);
System.out.println(map.size());
}
public static void demo2() {
Map<String, Integer> map = new HashMap<>();
map.put("张三", 23);
map.put("李四", 24);
map.put("王五", 25);
map.put("赵六", 26);
System.out.println(map.containsKey("张三"));
System.out.println(map.containsValue(100));
System.out.println(map);
}
public static void demo1() {
Map<String, Integer> map = new HashMap<>();
Integer i1 = map.put("张三", 23);
Integer i2= map.put("李四", 24);
Integer i3 = map.put("王五", 25);
Integer i4 = map.put("赵六", 26);
Integer i5 = map.put("张三", 26);
System.out.println(map);
System.out.println(i1);
System.out.println(i2);
System.out.println(i3);
System.out.println(i4);
System.out.println(i5);
}
}
2. Map集合的遍历
2.1. Map集合的遍历之键找值
- A:键找值思路:
- 获取所有键的集合
- 遍历键的集合,获取到每一个键
- 根据键找值
- B:案例演示
- Map集合的遍历之键找值
- map是双列集合,map中没有iterator方法所以遍历有以下两种方式
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Demo2_Iterator {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("张三", 23);
map.put("李四", 24);
map.put("王五", 25);
map.put("赵六", 26);
for(String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
}
}
2.2 Map集合的遍历之键值对对象找键和值
- A:键值对对象找键和值思路:
- 获取所有键值对对象的集合
- 遍历键值对对象的集合,获取到每一个键值对对象
- 根据键值对对象找键和值
- B:案例演示
HashMap<String, Integer> hm = new HashMap<>();
hm.put("张三", 23);
hm.put("李四", 24);
hm.put("王五", 25);
hm.put("赵六", 26);
for(Entry<String,Integer> en : hm.entrySet()) {
System.out.println(en.getKey() + "=" + en.getValue());
}