java 获取 Map中所有的 key 和 value 值

时间:2021-11-19 15:23:28

1、Student.java

package bo;

public class Student {
private String id ;
public Student(String id){
this.id = id;
}

@Override
public String toString() {
return " 学生:" + id ;
}


}

2、ClassRoom.java

package bo;

public class ClassRoom {
private String id;
public ClassRoom(String id ){
this.id = id;
}
@Override
public String toString() {
return "班级:" + id ;
}
}

3、Test.java

package bo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Test {
public static void main(String[] args) {
// 一班
Collection<Student> c1= new ArrayList<Student>();
ClassRoom classroom_1 = new ClassRoom("1班");
Student s1 = new Student("小明");
Student s2 = new Student("小红");
Student s3 = new Student("小光");
c1.add(s1);
c1.add(s2);
c1.add(s3);

// 二班
Collection<Student> c2 = new ArrayList<Student>();
ClassRoom classroom_2 = new ClassRoom("2班");
Student t1 = new Student("小黑");
Student t2 = new Student("小黄");
Student t3 = new Student("小米");
c2.add(t1);
c2.add(t2);
c2.add(t3);

Map<ClassRoom, Collection<Student>> m = new HashMap<ClassRoom,Collection<Student>>();
m.put(classroom_1, c1);
m.put(classroom_2, c2);

// 方法 一 :
// 转化成 Set<Entry<ClassRoom, Collection<Student>>>,然后在转化为迭代器
Iterator<Entry<ClassRoom, Collection<Student>>> iterator = m.entrySet().iterator();

while(iterator.hasNext()){
Entry<ClassRoom, Collection<Student>> entry = iterator.next();
System.out.println(entry.getKey()); // 获取key, 输出 ClassRoom
//System.out.println(entry.getValue()); // 获取value ,输出 Collection<Student>>
for(Student s : entry.getValue()){
System.out.println(s);
}
}

System.out.println("===");

// 方法 二 :
Iterator it = m.keySet().iterator(); // Set类型的key值集合,并转换为迭代器
while(it.hasNext()){
ClassRoom key = (ClassRoom) it.next(); // 获取 key 值,ClassRoom
System.out.println(key);
for(Student s : m.get(key)){ // 获取value 值,Collection (Student)
System.out.println(s);
}
}
/*
输出结果:
班级:1班
学生:小明
学生:小红
学生:小光
班级:2班
学生:小黑
学生:小黄
学生:小米
*/
}
}