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

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班
				   学生:小黑
				   学生:小黄
				   学生:小米
			*/   
	}
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值