目录
Map 集合
概念
特点
常用方法
遍历方式
Map 集合
概念
Map 集合提供了集合之间一种映射关系, 让集合和集合之间产生关系.
特点
能够存储唯一的列的数据 (唯一, 不可重复) Key 值.
能够存储可以重复的数据 (可重复) value 值.
值的顺序取决于键的顺序.
键和值都是可以存储 null 元素的.
一个映射不能包含重复的键, 每个键最多只能映射到一个值.
常用方法
1. 添加功能
- V put(K key, V value)
- void putAll(Map<? extends K,? extends V> m)
2. 删除功能
- V remove(Object key)
- void clear()
3. 遍历功能
- Set keySet()
- Collection values()
- Set<Map.Entry<K,V> entrySet()
4. 获取功能
V get(Object key)
5. 判断功能
- boolean containsKey(Object key)
- boolean containsValue(Object value)
- boolean isEmpty()
6. 修改功能
- V put(K key, V value)
- void putAll(Map<? extends K,? extends V> m)
7. 长度功能
int size()
遍历方式
方式 1: 根据 Key 查找 Value
Set<Key> set = map.keySet()
获取所有 Key 的集合 .
遍历 Key 的集合, 获取到每一个 Key .
根据 Key 查找 Value.
- public class Test {
- public static void main(String[] args) {
- Map<String,Integer> map = new HashMap<String,Integer>();
- map.put("张三", 18);
- map.put("李四", 19);
- map.put("王五", 18);
- map.put("赵六", 21);
- Set<String> ks = map.keySet();
- for(String s:ks){
- Integer i = map.get(s);
- System.out.println("姓名:"+s+"\t 年龄:"+i);
- }
- }
- }
方式 2: 根据键值对对象找键和值
Set<Map.Entry<Key, Value>> set = map.entrySet();
获取所有键值对对象的集合.
遍历键值对对象的集合, 获取到每一个键值对对象.
根据键值对对象找键和值.
- public class Test {
- public static void main(String[] args) {
- Map<String,Integer> map = new HashMap<String,Integer>();
- map.put("张三", 18);
- map.put("李四", 19);
- map.put("王五", 18);
- map.put("赵六", 21);
- Set<Entry<String,Integer>> mks = map.entrySet();
- for(Entry<String,Integer> ks :mks){
- String k = ks.getKey();
- Integer i = ks.getValue();
- System.out.println("姓名:"+k+"\t 年龄:"+i);
- }
- }
- }
以上
@Fzxey
Map 集合
来源: http://www.bubuko.com/infodetail-3043488.html