新建一个学生类,包含的成员变量有学号、姓名以及年龄,然后建立一个测试类,以学号作为键,学生类的对象作为值,保存到Map中,并实现输出,这里主要讲输出访时,核心就是迭代器。
package helloworld; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; public class StudentTest { public static void main(String[] args) { List<Student> stu = new ArrayList<Student>(); Student stu1 = new Student("1000", "aaa", 18); Student stu2 = new Student("1001", "bbb", 19); Student stu3 = new Student("1002", "ccc", 18); Student stu4 = new Student("1001", "ddd", 20); stu.add(stu1); stu.add(stu2); stu.add(stu3); stu.add(stu4); Iterator<Student> it = stu.iterator(); while(it.hasNext()){ System.out.println(it.next()); } Collections.sort(stu, new Comparator<Student>(){ @Override public int compare(Student o1, Student o2) { if(o1.id.compareTo(o2.id) == 0){ return o1.age-o2.age; } return o1.id.compareTo(o2.id); } }); System.out.println("-----------"); Iterator<Student> it1 = stu.iterator(); while(it1.hasNext()){ System.out.println(it1.next()); } } }
package helloworld; import java.util.*; import java.util.Map.Entry; public class StudentTest3 { public static void main(String[] args) { Map<String, Student> map = new HashMap<String, Student>(); Student stu1 = new Student("1000", "aaa", 18); Student stu2 = new Student("1001", "bbb", 19); Student stu3 = new Student("1002", "ccc", 18); Student stu4 = new Student("1003", "ddd", 20); map.put(stu1.id, stu1); map.put(stu2.id, stu2); map.put(stu3.id, stu3); map.put(stu4.id, stu4); //1\利用键值对 Set<String> keyset = map.keySet(); Iterator<String> it = keyset.iterator(); while(it.hasNext()){ String nextkey = it.next(); Student obj = map.get(nextkey); System.out.println(nextkey +"--"+obj); } System.out.println("************"); //2利用键值对德集合 Set<Entry<String, Student>> entrySet = map.entrySet(); Iterator<Entry<String, Student>> it1 = entrySet.iterator(); while(it1.hasNext()){ Entry<String, Student> entry = it1.next(); String id = entry.getKey(); Student stu = entry.getValue(); System.out.println(id+"---"+stu); } System.out.println("************"); //3 Collection<Student> col = map.values(); Iterator<Student> it2 = col.iterator(); while(it2.hasNext()){ Student stu0 = it2.next(); System.out.println("----"+stu0); } } }