Java的map键值对的用法,map的遍历,Entry对象的使用

时间:2023-03-09 03:34:00
Java的map键值对的用法,map的遍历,Entry对象的使用

思路:

1、定义集合

2、存储数据

3、添加元素

4、遍历

  4.1将需要遍历的集合的键封装到set集合中(这用到了entrySet方法,和Entry对象)

  4.2声明迭代器或者用for增强循环

  4.3通过set集合的getKey和getValue方法拿到值和键

5、打印输出就好

代码呈现如下:

 package com.aaa.demo;

 import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set; public class MaoMapDemo {
public static void main(String[] args) {
//定义Java班的集合
HashMap<String, String> javas=new HashMap<String,String>();
//定义Hdoop班的集合
HashMap<String, String> Hdoop=new HashMap<String,String>();
//向班级存储学生
javas.put("001", "大冰");
javas.put("002", "北岛"); Hdoop.put("001", "舒婷");
Hdoop.put("002", "食指");
//定义aaa容器,键是班级的名字 值是两个班级的容器
HashMap<String, HashMap<String, String>> aaa=new HashMap<String,HashMap<String,String>>();
aaa.put("现代", javas);
aaa.put("近代", Hdoop);
entrySet1(aaa);
}
public static void entrySet(HashMap<String,HashMap<String,String>> aaa){
//调用集合aaa的方法 entrySet将aaa集合的键封装到Set集合中
Set<Entry<String,HashMap<String,String>>> classNameSet=aaa.entrySet();
//迭代Set集合
Iterator<Entry<String,HashMap<String,String>>> it=classNameSet.iterator();
while(it.hasNext()){
Entry<String,HashMap<String,String>> next=it.next();
//getKey getValue 得到键和值
String classNameKey = next.getKey();
System.out.println(classNameKey);
//aaa容器的键 班级姓名classMap
HashMap<String,String> classMap=next.getValue();
//entrySet将classMap集合的键封装到set集合中
Set<Entry<String,String>> studentSet=classMap.entrySet();
//迭代
Iterator<Entry<String, String>> studentIt = studentSet.iterator();
while(studentIt.hasNext()){
//遍历集合
Entry<String,String> studentEntry=studentIt.next();
String numKey = studentEntry.getKey();
String nameValue = studentEntry.getValue();
System.out.println(numKey+": "+nameValue);
}
}
}
public static void entrySet1(HashMap<String,HashMap<String,String>> aaa){
//调用集合aaa的方法 entrySet将aaa集合的键封装到Set集合中
Set<Entry<String,HashMap<String,String>>> cNS=aaa.entrySet();
//for循环遍历得到班级
for(Entry<String,HashMap<String,String>> next:cNS){
//getKey getValue 得到键和值
String classKey = next.getKey();
//aaa容器的键 班级姓名classMap
HashMap<String, String> classValue = next.getValue();
//entrySet将classMap集合的键封装到set集合中
Set<Entry<String, String>> studentSet = classValue.entrySet();
System.out.println(classKey);
//for循环遍历
//Set<Entry<String, String>> entrySet = classValue.entrySet();
for(Entry<String, String> studentEntry:studentSet){
String numKey = studentEntry.getKey();
String nameValue = studentEntry.getValue();
System.out.println(numKey+": "+nameValue);
}
}
}
}