- 键找值方式:即通过元素中的键,获取键所对应的值
操作步骤:
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=小罗],成都
- 键值对方式:即通过集合中每个键值对(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=小罗],成都