Day04
目录
Map集合
1.1 有关Map集合的简介
1.2 Map集合与Collection集合的区别
1.3 Map集合常用子类
1.4 Map接口常用方法
1.5 常用遍历HashMap的方法
1.6 练习:字符串中每个字符出现的次数
一、 Map集合
1.1有关Map集合的简介
Map集合中的数据是成对储存的,Map接口下有两个子类:
-
HashMap
-
LinkedHashMap
其中HashMap是无序集合,LinkedHashMap是有序集合。
Map接口下的集合采用键值对储存数据—:<Key,Value>,每一个Key值对应一个Value,Key和Value代表一种类型。
这种一一对应的关系,就叫做映射
1.2Map集合与Collection集合的区别
-
Map集合称为双列集合,而Collection集合称作单列集合
-
Collection中存储的元素是单独存在。Map集合中是成对存在的,可以通过Key值检索对应的Value
-
Map集合中Key值不可以重复,但是Value可以重复
1.3Map集合常用子类
- HashMap<K,V> 无序集合
- HashMap的子类:LinkedHashMap<K,V> 有序集合,存储数据采用哈希表结构+链表结构。
为了保证键(Key)的唯一不重复,这两类均需要重写hashCode与equals方法。
1.4 Map接口常用方法
-
public V put(K key,V value)
将指定键添加到集合中,如果集合中不存在此键,则返回null,如果已经存在此键,则返回添加之前的Value,并用新Value代替旧Value -
public V remove(Object key)
删除集合中指定的键及其对应的键值 -
public V get(K key)
根据指定的键,获得对应的值。 -
public boolean containsKey(Object key)
判断集合中是否包含指定的键 -
public boolean isEmpty()
判断该Map集合是否为空 -
public Set<key> keySet()
返回键值的集合 -
public Set<Entry<K,V>> entrySet()
返回键值对对象Entry的集合public static void main(String[] args) { HashMap<String,String> map = new HashMap<String,String>(); map.put("1", "first"); map.put("2", "second"); map.put("3", "third"); System.out.println(map); System.out.println(map.remove("1")); Set<String> set = map.keySet(); System.out.println(set); Set<Entry<String,String>> setentry=map.entrySet(); System.out.println(setentry); System.out.println(map.containsKey("2")+" "+map.containsKey("1")); /* 输出结果:{1=first, 2=second, 3=third} first [2, 3] [2=second, 3=third] true false */ }
1.5 常用遍历方法
-
利用keySet()方法,获得键集合,遍历键,根据键值获得Value
-
利用entrySet()方法,获得键值对对象Entry的集合,从而遍历map
Entry将键值对的关系封装成了对象,它表示了一对键和值,这一对对象成为Map里的Entry(项),它也提供了获取对应键和对应值得方法:
public K getKey()
:获取Entry对象中的键。public V getValue()
:获取Entry对象中的值。
Set<String> set = map.keySet(); System.out.println(set); Set<Entry<String,String>> setentry=map.entrySet(); System.out.println(setentry); //使用for-each循环,遍历key值,根据key值获得Value。或者根据Entry直接遍历K与V for(String s :set) { System.out.println(s+" "+map.get(s)); } for(Entry<String,String> s:setentry) { System.out.println(s.getKey()+" "+s