hashmap的键查找遍历与键值对查找遍历

  1. 键找值方式:即通过元素中的键,获取键所对应的值
    操作步骤:
    1.获取Map集合中所有的键,由于键是唯一的,所以返回一个Set集合存储所有的键
    2.遍历键的Set集合,得到每一个键
    3.根据键,获取键所对应的值

注意:本例子之前还先写了个student类,重写了hashcode ,equals和tostring方法。
回顾请看:hashset中重写equals方法和 hashCode方法

public class test {
	public static void main(String[] args) {
		HashMap<student, String> a=new HashMap<student, String>();
		a.put(new student("岳帅",22), "成都");
		a.put(new student("岳帅",22), "成都");
		a.put(new student("小马",22), "绵阳");
		a.put(new student("小周",22), "乐山");
		a.put(new student("小罗",21), "成都");
		//通过键找值
		Set<student> stu=a.keySet();
		//增强for遍历
		for(student k:stu) {
			String b=a.get(k);
			System.out.println(k.toString()+","+b);
			}
		//迭代器遍历
		Iterator<student> stu3=stu.iterator();
		while(stu3.hasNext()) {
			student k=stu3.next();
			String value=a.get(k);
			System.out.println(k.toString()+","+value);
		}
		}
两个结果相同只写一个:	
		student [age=22, name=小马],绵阳
		student [age=22, name=岳帅],成都
		student [age=22, name=小周],乐山
		student [age=21, name=小罗],成都
  1. 键值对方式:即通过集合中每个键值对(Entry)对象,获取键值对(Entry)对象中的键与值。
    操作步骤与:

    1.获取Map集合中,所有的键值对(Entry)对象,以Set集合形式返回。
    2.遍历包含键值对(Entry)对象的Set集合,得到每一个键值对(Entry)对象
    3.通过键值对(Entry)对象,获取Entry对象中的键与值。
    getkey()获取键,getvalue()获取值
public class test2 {

	public static void main(String[] args) {
		HashMap<student, String> a=new HashMap<student, String>();
		a.put(new student("岳帅",22), "成都");
		a.put(new student("岳帅",22), "成都");
		a.put(new student("小马",22), "绵阳");
		a.put(new student("小周",23), "乐山");
		a.put(new student("小罗",21), "成都");
		
		Set<Entry<student,String>> a2=a.entrySet();
		
		for(Entry<student,String> k:a2) {
			student key=k.getKey();
			String value=k.getValue();
			System.out.println(key.toString()+","+value);
		}
		Iterator<Entry<student,String>> a3=a2.iterator();
		while(a3.hasNext()) {
			Entry<student, String> k= a3.next();
			System.out.println(k.getKey().toString()+","+k.getValue());	
		}
	}
}
两个结果相同只写一个:
		student [age=22, name=小马],绵阳
		student [age=22, name=岳帅],成都
		student [age=23, name=小周],乐山
		student [age=21, name=小罗],成都
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值