集合的一個很重要的操做---遍歷,學習了三種遍歷方法,三種方法各有優缺點~~ java
1. eclipse
package com.myTest.MapText; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class TestMap { //1. 最常規的一種遍歷方法,最常規就是最經常使用的,雖然不復雜,但很重要,這是咱們最熟悉的,就很少說了!! public static void work(Map<String, Student> map) { Collection<Student> c = map.values(); Iterator<Student> it = c.iterator(); for (; it.hasNext();) { System.out.println(it.next()); } // 當for循環只有一個判斷語句的時候,就等同於while循環了 // while(it.hasNext()) // { // System.out.println(it.next()); // } } // 2.利用keyset進行遍歷,它的優勢在於能夠根據你所想要的key值獲得你想要的 values,更具靈活性!! public static void workByKeySet(Map<String, Student> map) { Set<String> key = map.keySet(); Iterator<String> it = key.iterator(); for (; it.hasNext();) { String s = (String) it.next(); System.out.println(map.get(s)); } //用加強型for循環也可 // for(Object o : map.keySet()) // { // System.out.println(map.get(o)); // } } // 3.比較複雜的一種遍歷在這裏,呵呵~~他很暴力哦,它的靈活性太強了,想獲得什麼就能獲得什麼~ public static void workByEntry(Map<String, Student> map) { Set<Map.Entry<String, Student>> set = map.entrySet(); Iterator<Map.Entry<String, Student>> it = set.iterator(); for (; it.hasNext();) { Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next(); // System.out.println(entry.getKey() + "--->" + entry.getValue()); System.out.println(entry.getValue()); } } public static void main(String[] args) { Map<String, Student> map = new HashMap<String, Student>(); Student s1 = new Student("宋江", "1001", 38); Student s2 = new Student("盧俊義", "1002", 35); Student s3 = new Student("吳用", "1003", 34); map.put("1001", s1); map.put("1002", s2); map.put("1003", s3); Map<String, Student> subMap = new HashMap<String, Student>(); subMap.put("1008", new Student("tom", "1008", 12)); subMap.put("1009", new Student("jerry", "1009", 10)); map.putAll(subMap); // work(map); workByKeySet(map); // workByEntry(map); } }
2. ide
package com.myTest.MapText; public class Student { private String name; private String id; private int age; public Student(String name, String id, int age) { this.name = name; this.id = id; this.age = age; } @Override public String toString() { return "Student{" + "name=" + name + " id=" + id + " age=" + age + '}'; } }
可直接複製代碼到Myeclipse工具中運行看結果。 工具