import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Student2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Student> m = new HashMap<String, Student>();
Student s1 = (new Student(18,"Lihua", "1"));
Student s2 = (new Student(20, "xiaohong", "2"));
Student s3 = (new Student(65, "xiaoMing", "3"));
m.put("111", s1);
m.put("222", s2);
m.put("333", s3);
//1
Set<String> kk = m.keySet();
Iterator<String> it = kk.iterator();
while(it.hasNext())
{
String k1 = it.next();
Student st = m.get(k1);
System.out.println(st);
}
//2
Set<Entry<String, Student>> en = m.entrySet();
Iterator<Entry<String, Student>> it2 = en.iterator();
while(it2.hasNext())
{
Entry<String, Student> ne = it2.next();
Student value = ne.getValue();
String key = ne.getKey();
System.out.println(key);
System.out.println(value);
}
//3
Collection<Student> c = m.values();
Iterator<Student> it3 = c.iterator();
while(it3.hasNext())
{
Student next = it3.next();
System.out.println(next);
}
}
}java map展开
最新推荐文章于 2022-12-15 16:46:32 发布
本文通过一个具体的Java代码示例介绍了如何使用三种不同的方法来遍历HashMap:1) 通过keySet获取所有的键,然后逐个取出对应的值;2) 通过entrySet获取所有的键值对,并分别处理键与值;3) 直接获取所有值进行遍历。这些方法对于理解HashMap的工作原理及其在实际应用中的使用非常有用。
645

被折叠的 条评论
为什么被折叠?



