集合的一个很重要的操作---遍历,学习了三种遍历方法,自己记录下来,三种方法各有优缺点~~
1 /* 2 * To change this template, choose Tools | Templates 3 * and open the template in the editor. 4 */ 5 import java.util.Collection; 6 import java.util.HashMap; 7 import java.util.Iterator; 8 import java.util.Map; 9 import java.util.Set; 10 import java.util.TreeMap; 11 12 /** 13 * 14 * @author Administrator 15 */ 16 public class TestMap { 17 18 public static void main(String[] args) { 19 Map<String, Student> map = new HashMap<String, Student>(); 20 Student s1 = new Student("宋江", "1001", 38); 21 Student s2 = new Student("卢俊义", "1002", 35); 22 Student s3 = new Student("吴用", "1003", 34); 23 24 map.put("1001", s1); 25 map.put("1002", s2); 26 map.put("1003", s3); 27 28 Map<String, Student> subMap = new HashMap<String, Student>(); 29 subMap.put("1008", new Student("tom", "1008", 12)); 30 subMap.put("1009", new Student("jerry", "1009", 10)); 31 map.putAll(subMap); 32 33 work(map); 34 workByKeySet(map); 35 workByEntry(map); 36 } 37 38 //最常规的一种遍历方法,最常规就是最常用的,虽然不复杂,但很重要,我们最熟悉的 39 public static void work(Map<String, Student> map) { 40 Collection<Student> c = map.values(); 41 Iterator it = c.iterator(); 42 for (; it.hasNext();) { 43 System.out.println(it.next()); 44 } 45 } 46 47 //利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values,更具灵活性!! 48 49 public static void workByKeySet(Map<String, Student> map) { 50 Set<String> key = map.keySet(); 51 for (Iterator it = key.iterator(); it.hasNext();) { 52 String s = (String) it.next(); 53 System.out.println(map.get(s)); 54 } 55 } 56 57 //比较复杂的一种遍历在这里,很灵活 58 59 public static void workByEntry(Map<String, Student> map) { 60 Set<Map.Entry<String, Student>> set = map.entrySet(); 61 for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) { 62 Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next(); 63 System.out.println(entry.getKey() + "--->" + entry.getValue()); 64 } 65 } 66 } 67 68 class Student { 69 70 private String name; 71 private String id; 72 private int age; 73 74 public Student(String name, String id, int age) { 75 this.name = name; 76 this.id = id; 77 this.age = age; 78 } 79 80 @Override 81 public String toString() { 82 return "Student{" + "name=" + name + "id=" + id + "age=" + age + '}'; 83 } 84 }