- 5.1Map集合的概述和使用
- 5.1.1HashMap的put方法
- 5.2 Map集合的基本功能
- 5.3 Map集合的获取功能
- 5.4 Map集合的遍历(方式1:将键获取到一个集合,再将键的集合遍历获取对应的值)
- 5.5 Map集合的遍历(方式2:获取键值对象Map.Entry,然后遍历)
- 5.7 案例:HashMap集合存储集合对象并遍历(保证键唯一,在类中重写equals()和hashCode()方法)
- 5.8 案例:ArrayList集合存储HashMap元素并遍历
- 5.9 案例:HashMap集合存储ArrayList元素并遍历
- 5.10 案例:统计字符串中每个字符出现的次数
Interface Map
K:Map集合中key的类型
V:Map集合中value的类型
All Known Implementing Classes:
AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, Headers, IdentityHashMap, linkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap
public interface Map
1.Interface Map
K:Map集合中key的类型
V:Map集合中value的类型
2.将键映射到值得对象,Map不能包含重复的键,每个键可以映射到最多一个值
3.举例:学生的学号和姓名
student1 “anna”
student2 “tom”
student3 “we”
创建Map结合的对象:
因为Map是接口,不能直接创建对象,所以我们使用多态的方式来创建.在这里我们可以创建实现类HashMap的对象
举例:学生的学号和姓名
student1 “anna”
student2 “tom”
student3 “we”
HashMap的元素的添加我们使用put方法,注意如果key一次出现时是添加此元素,如果key第二次出现时,是修改元素.
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map map=new HashMap<>();
map.put("student1","anna");
map.put("student2","tom");
map.put("student3","we");
map.put("student3","change");
System.out.println(map);
}
}
输出结果:
{student2=tom, student1=anna, student3=change}
注意:
这里的HashMap重写了toString方法,这里的输出结果用=号连接.
key第二次出现时,value会覆盖.
| 方法名 | 说明 |
|---|---|
| V put(K key,V value) | 添加元素 |
| V remove(Object key) | 根据键删除键值对元素 |
| void clear() | 删除Map集合中所有的元素 |
| boolean containsKey(Object value) | 判断集合是否包含指定的值 |
| boolean isEmpty() | 判断集合是否为空 |
| int size() | 集合的长度,也就是集合中键值对的个数 |
import java.util.HashMap;
import java.util.Map;
public class MapDemo01 {
public static void main(String[] args) {
Map m=new HashMap();
m.put("zwj","zm");
m.put("gj","hr");
m.put("yg","xln");
m.remove("zwj");
System.out.println(m);
System.out.println(m.containsKey("gj"));
System.out.println(m.containsValue("zm"));
System.out.println(m.isEmpty());
System.out.println(m.size());
m.clear();
System.out.println(m.size());
}
}
输出结果:
{gj=hr, yg=xln}
true
false
false
2
0
5.3 Map集合的获取功能
| 方法名 | 说明 |
|---|---|
| V get(Object key) | 根据键获取值 |
| SetkeySet() | 获取所有键的集合 |
| Collectionvalues() | 获取所有值的集合 |
| Set | 获取所有键值对象的集合 |
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo02 {
public static void main(String[] args) {
Map map=new HashMap();
map.put("first","anan");
map.put("second","bob");
map.put("third","cow");
map.put("fourth","dead");
System.out.println(map.get("fourth"));
System.out.println("-----");
System.out.println(map.keySet());
Set ketSet=map.keySet();
for(String s:ketSet){
System.out.println(s);
}
System.out.println("-----");
System.out.println(map.values());
Collection collection=map.values();
for(String s:collection){
System.out.println(s);
}
System.out.println("-----");
System.out.println(map.entrySet());
Set> setMapEntry = map.entrySet();
System.out.println(setMapEntry);
}
}
输出结果:
dead ----- [third, fourth, first, second] third fourth first second ----- [cow, dead, anan, bob] cow dead anan bob ----- [third=cow, fourth=dead, first=anan, second=bob] [third=cow, fourth=dead, first=anan, second=bob]5.4 Map集合的遍历(方式1:将键获取到一个集合,再将键的集合遍历获取对应的值)
Map存储的元素都是键值对的形式成对出现的.
遍历思路:
1、把所有键的放到一个集合;
2、遍历键的集合,获取到每一个键;
3、根据键的获取到键对应的每一个值。
转换成Map结合中的操作为:
1、Set.setKey()
2、for()
3、V get(Object key)
import java.util.*;
public class MapSimple01 {
public static void main(String[] args) {
Map mapStudent=new HashMap();
mapStudent.put(1,"A");
mapStudent.put(2,"B");
mapStudent.put(3,"C");
mapStudent.put(4,"C");
mapStudent.put(5,"D");
System.out.println(mapStudent);
Set studentNumSet = mapStudent.keySet();
for(int key:studentNumSet){
String value=mapStudent.get(key);
System.out.println(key+"="+value);
}
}
}
输出结果:
{1=A, 2=B, 3=C, 4=C, 5=D}
1=A
2=B
3=C
4=C
5=D
5.5 Map集合的遍历(方式2:获取键值对象Map.Entry,然后遍历)
Map存储的集合都是键值对的形式成对出现的,所以我们可以将键值对看成一个大的集合。
遍历思路:
1、获取所有键值对的集合
2、遍历键值对集合,得到每一个键值对
3、根据键值对,分别获取键和值
转换成Map集合中的操作:
1、获取所有键值对对象的集合;
Set
2、遍历键值对对象的集合,得到每一个键值对对象
用增强for循环实现,得到每一个Map.Entry
3、根据键值对对象获取键和值
用getKey()获取键;
用getValue()获取值。
package daily_Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapSimple02 {
public static void main(String[] args) {
Map mapCircle=new HashMap<>();
mapCircle.put(1,"A");
mapCircle.put(2,"B");
mapCircle.put(3,"C");
mapCircle.put(4,"C");
mapCircle.put(5,"D");
System.out.println(mapCircle);
Set> mapEntrySet =mapCircle.entrySet();
for(Map.Entry me:mapEntrySet){
Integer meKey=me.getKey();
String mevalue=me.getValue();
System.out.println(meKey);
System.out.println(mevalue);
}
}
}
输出结果:
```java
{1=A, 2=B, 3=C, 4=C, 5=D}
1
A
2
B
3
C
4
C
5
D
# 5.6 案例:HashMap集合存储学生对象并遍历
需求:创建一个HashMap集合,键是学号String,值是学生对象Student。存储三个键值元素,并遍历。
思路:
1.定义学生类
2.创建HashMap集合
3.创建学生对象
4.将学生对象添加到集合中
5.遍历集合
遍历方式1:根据键找值
遍历方式2:根据键值对象找键和值
```java
package daily_Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapSimpleObj {
public static void main(String[] args) {
Map hashMapStudent=new HashMap<>();
Student s1=new Student("LUNA",10);
Student s2=new Student("BOB",12);
Student s3=new Student("Cathy",45);
Student s4=new Student("David",54);
hashMapStudent.put("202201",s1);
hashMapStudent.put("202202",s2);
hashMapStudent.put("202203",s3);
hashMapStudent.put("202204",s4);
System.out.println(hashMapStudent);
Set keySet=hashMapStudent.keySet();
for (String key:keySet){
Student value=hashMapStudent.get(key);
System.out.println(key+":"+value.getName()+"+"+value.getAge());
}
System.out.println("-------------------------");
Set> hashMapEntry=hashMapStudent.entrySet();
for (Map.Entry hme:hashMapEntry){
String key=hme.getKey();
String valueName=hme.getValue().getName();
Integer valueAge=hme.getValue().getAge();
System.out.println(key+":"+valueName+","+valueAge);
}
}
}
输出结果:
{202201=daily_Map.Student@4554617c, 202204=daily_Map.Student@74a14482, 202202=daily_Map.Student@1540e19d, 202203=daily_Map.Student@677327b6}
202201:LUNA+10
202204:David+54
202202:BOB+12
202203:Cathy+45
-------------------------
202201:LUNA,10
202204:David,54
202202:BOB,12
202203:Cathy,45
5.7 案例:HashMap集合存储集合对象并遍历(保证键唯一,在类中重写equals()和hashCode()方法)
需求:创建一个HashMap集合,键是学生对象Student,值是居住地String。存储多个键值对元素,并遍历。
要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象。
思路:
1.定义学生类
2.创建HashMap集合对象
3.创建学生对象
4.把学生添加到集合
5.遍历集合
6.在学生类中重写两个方法来保证键的唯一性
hashCode();
equals();
package daily_Map;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
package daily_Map;
import java.util.HashMap;
import java.util.Set;
public class MapSimpleKeyUnique {
public static void main(String[] args) {
HashMap hm =new HashMap<>();
Student s1=new Student("LUNA",10);
Student s2=new Student("BOB",12);
Student s3=new Student("Cathy",45);
Student s4=new Student("David",54);
Student s5=new Student("David",54);
hm.put(s1,"西安");
hm.put(s2,"武汉");
hm.put(s3,"郑州");
hm.put(s4,"北京");
hm.put(s5,"长沙");
Set students=hm.keySet();
for(Student key: hm.keySet()){
String value=hm.get(key);
System.out.println(key.getName()+","+key.getAge()+","+value);
}
}
}
输出结果:
David,54,长沙 Cathy,45,郑州 LUNA,10,西安 BOB,12,武汉
如果Student类中不重写hashCod()和equals()方法,输出的结果为:
BOB,12,武汉 David,54,北京 LUNA,10,西安 Cathy,45,郑州 David,54,长沙5.8 案例:ArrayList集合存储HashMap元素并遍历
需求:创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是String,并遍历。
思路:
1.创建ArrayList集合
2.创建HashMap集合,并添加键值对元素
3.把HashMap作为元素添加到ArrayList集合
4.遍历ArrayList集合
package daily_Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
public class MapSimpleArrayList {
public static void main(String[] args) {
ArrayList> array=new ArrayList<>();
HashMap hm1=new HashMap<>();
hm1.put("孙策","大乔");
hm1.put("周瑜","小乔");
array.add(hm1);
HashMap hm2=new HashMap<>();
hm2.put("郭靖","黄蓉");
hm2.put("杨过","小龙女");
array.add(hm2);
HashMap hm3=new HashMap<>();
hm3.put("令狐冲","任盈盈");
hm3.put("林平之","岳灵珊");
array.add(hm3);
for(HashMap hashM:array){
Set keySet=hashM.keySet();
for(String key:keySet){
String value=hashM.get(key);
System.out.println(key+","+value);
}
}
}
}
输出结果:
孙策,大乔 周瑜,小乔 杨过,小龙女 郭靖,黄蓉 令狐冲,任盈盈 林平之,岳灵珊5.9 案例:HashMap集合存储ArrayList元素并遍历
需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList,每一个ArrayList的元素是String,并遍历。
思路:
1.创建HashMap集合
2.创建ArrayList对象
3.创建ArrayList对象添加到HashMap集合中
4.遍历HashMap集合
package daily_Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapSimpleHashMap {
public static void main(String[] args) {
Map> mapArrayList =new HashMap<>();
ArrayList arrayList1=new ArrayList();
arrayList1.add("诸葛亮");
arrayList1.add("赵云");
arrayList1.add("吕布");
mapArrayList.put("三国演义",arrayList1);
ArrayList arrayList2=new ArrayList();
arrayList2.add("孙悟空");
arrayList2.add("猪八戒");
arrayList2.add("唐僧");
arrayList2.add("沙和尚");
arrayList2.add("白骨精");
mapArrayList.put("西游记",arrayList2);
System.out.println(mapArrayList);
ArrayList arrayList3=new ArrayList();
arrayList3.add("武松");
arrayList3.add("鲁智深");
mapArrayList.put("水浒传",arrayList3);
Set keySet=mapArrayList.keySet();
for (String key:keySet){
ArrayList array=mapArrayList.get(key);
System.out.println("著作名:"+key);
for(String s:array){
System.out.println(s);
}
System.out.println("----------------");
}
}
}
输出结果:
{三国演义=[诸葛亮, 赵云, 吕布], 西游记=[孙悟空, 猪八戒, 唐僧, 沙和尚, 白骨精]}
著作名:水浒传
武松
鲁智深
----------------
著作名:三国演义
诸葛亮
赵云
吕布
----------------
著作名:西游记
孙悟空
猪八戒
唐僧
沙和尚
白骨精
----------------
5.10 案例:统计字符串中每个字符出现的次数
需求:键盘录入一个字符串,要求统计字符串中每个字符出现的次数
举例:”aabcdddd“ 输出:”a(2)b(1)c(1)d(4)“
分析:
键:字符,值:出现的次数,可以用HashMap集合来存储
note:键是字符,类型应该是Character;值是字符出现的次数,类型因该是Integer。
思路:
1.键盘录入一个字符串
2.创建HashMap集合,键是Character,值是Integer
3.遍历字符串得到每一个字符
4.将此字符做为键到HashMap集合中找对应的值,看返回值:
如果返回值为null:说明该字符在HashMap集合中不存在,就把该字符作为键,1为值
如果返回值不为null:说明该字符在HashMap集合中存在,就把值加1,然后存储该字符和对应的值,如果重复会覆盖,值继续加1
5.遍历HashMap集合,得到键和值,按要求进行拼接。
package daily_Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class MapCalCharNum {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("input a String please!");
String line=sc.nextLine();//获取输入的字符
System.out.println(line);
Map hashMap=new HashMap<>();
for (int i=0;i> hmSet=hashMap.entrySet();
StringBuilder sb = new StringBuilder();
for(HashMap.Entry hm:hmSet){
Character k = hm.getKey();
Integer v = hm.getValue();
sb.append(k+"("+v+")");
}
String res = sb.toString();
System.out.println(res);
// System.out.println("-------------------");
// StringBuilder sb = new StringBuilder();
// Set keySet = hashMap.keySet();
// System.out.println(keySet);
// for (Character key:keySet){
// Integer value = hashMap.get(key);
// sb.append(key).append("(").append(value).append(")");
// }
// String s = sb.toString();
// System.out.println(s);
}
}
输出结果:
input a String please!
adccccccced
adccccccced
{a=1, c=7, d=2, e=1}
a(1)c(7)d(2)e(1)



