`

遍历map的三种方法

    博客分类:
  • java
map 
阅读更多
  1. package cn.tsp2c.liubao;   
  2. import java.util.Collection;   
  3. import java.util.HashMap;   
  4. import java.util.Iterator;   
  5. import java.util.Map;   
  6. import java.util.Set;   
  7. import java.util.TreeMap;   
  8.   
  9. public class TestMap {   
  10.     public static void main(String[] args) {   
  11.         Map<String, Student> map = new HashMap<String, Student>();   
  12.         Student s1 = new Student("宋江""1001"38);   
  13.         Student s2 = new Student("卢俊义""1002"35);   
  14.         Student s3 = new Student("吴用""1003"34);   
  15.            
  16.         map.put("1001", s1);   
  17.         map.put("1002", s2);   
  18.         map.put("1003", s3);   
  19.         Map<String, Student> subMap = new HashMap<String, Student>();   
  20.         subMap.put("1008"new Student("tom""1008"12));   
  21.         subMap.put("1009"new Student("jerry""1009"10));   
  22.         map.putAll(subMap);   
  23.         work(map);   
  24.         workByKeySet(map);   
  25.         workByEntry(map);   
  26.     }   
  27.   [color=red]最常规的一种遍历方法,最常规就是最常用的,虽然不复杂,但很重要,这是我们最熟悉的,就不多说了!![/color]   
  28.  public static void work(Map<String, Student> map) {   
  29.         Collection<Student> c = map.values();   
  30.         Iterator it = c.iterator();   
  31.         for (; it.hasNext();) {   
  32.             System.out.println(it.next());   
  33.         }   
  34.     }   
  35.   [color=red]利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values,更具灵活性!![/color]   
  36.  public static void workByKeySet(Map<String, Student> map) {   
  37.         Set<String> key = map.keySet();   
  38.         for (Iterator it = key.iterator(); it.hasNext();) {   
  39.             String s = (String) it.next();   
  40.             System.out.println(map.get(s));   
  41.         }   
  42.     }   
  43.   
  44.   [color=red]比较复杂的一种遍历在这里,呵呵~~他很暴力哦,它的灵活性太强了,想得到什么就能得到什么~~[/color]   
  45.  public static void workByEntry(Map<String, Student> map) {   
  46.         Set<Map.Entry<String, Student>> set = map.entrySet();   
  47.         for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {   
  48.             Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();   
  49.             System.out.println(entry.getKey() + "--->" + entry.getValue());   
  50.         }   
  51.     }   
  52. }   
  53. class Student {   
  54.     private String name;   
  55.     private String id;   
  56.     private int age;   
  57.     public Student(String name, String id, int age) {   
  58.         this.name = name;   
  59.         this.id = id;   
  60.         this.age = age;   
  61.     }   
  62.     @Override  
  63.     public String toString() {   
  64.         return "Student{" + "name=" + name + "id=" + id + "age=" + age + '}';   
  65.     }   
  66. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics