概述
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* @author Administrator
*/
public class StuMapTest {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<String, Student>();
Student s1 = new Student("001", "吕布", 30);
Student s2 = new Student("002", "赵云", 25);
Student s3 = new Student("003", "典韦", 33);
map.put("1", s1);
map.put("2", s2);
map.put("3", s3);
byValues(map);
keySet(map);
entrySet(map);
}
//entrySet方法遍历
private static void entrySet(Map<String, Student> map){
Set<Map.Entry<String,Student>> set = map.entrySet();
for (Iterator<Map.Entry<String, Student>> i = set.iterator(); i.hasNext();) {
System.out.println(i.next().getValue());
}
}
//keySet方法遍历
private static void keySet(Map<String, Student> map){
Set<String> set = map.keySet();
for (Iterator<String> i = set.iterator(); i.hasNext();) {
System.out.println(map.get(i.next()));
}
}
//values方法遍历
private static void byValues(Map<String, Student> map) {
Collection c = map.values();
for (Iterator<Student> i = c.iterator(); i.hasNext();) {
System.out.println(i.next());
}
}
}
//定义一个student类
class Student {
private String id;
private String name;
private int age;
public Student(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return new StringBuilder().append(id).append(" ").append(name).append(" ").append(age).toString();
}
}
转载于:https://www.cnblogs.com/wingteam/archive/2010/10/30/1865219.html
最后
以上就是含蓄小伙为你收集整理的HashMap集合的三种迭代方法的全部内容,希望文章能够帮你解决HashMap集合的三种迭代方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复