熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Map遍歷方法

2013-11-23 18:58:50  來源: Java核心技術 

  Java代碼

  Map map = new HashMap();

  Iterator it = mapentrySet(erator();

  while (ithasNext()) {

  MapEntry entry = (MapEntry) itnext();

  Object key = entrygetKey();

  Object value = entrygetValue();

  }

  JDK應用新特性ForEach循環

  Java代碼

  Map m = new HashMap();

  for(Object o : mapkeySet()){

  mapget(o);

  }

  返回的 set 中的每個元素都是一個 MapEntry 類型

  private Hashtable<String String> emails = new Hashtable<String String>();

  另外 我們可以先把hashMap 轉為集合Collection再迭代輸出不過得到的對象

  //方法一: 用entrySet()

  Java代碼

  Iterator it = emailsentrySet(erator();

  while(ithasNext()){

  MapEntry m=(MapEntry)itnext();

  (email + mgetKey() + : + mgetValue());

  }

  // 方法二jdk支持用entrySet()和ForEach循環()

  Java代碼

  for (MapEntry<String String> m : emailsentrySet()) {

  (email + mgetKey() + : + mgetValue());

  }

  // 方法三用keySet()

  Java代碼

  Iterator it = emailskeySet(erator();

  while (ithasNext()){

  String key;

  key=(String)itnext();

  (email + key + : + emailsget(key));

  }

  // 方法四jdk支持用keySEt()和ForEach循環

  Java代碼

  for(Object m: emailskeySet()){

  (email + m+ : + emailsget(m));

  }
          Map    aa    =    new    HashMap();
     aaput(tmp    new    Object());
    //追加      替換用同樣的函數
    aaremove(temp);
    //刪除
    for    (Iterator    i    =    aavalues(erator();    ihasNext();    )    {              Object    temp    =    inext();      }
     //遍歷

  來個完整的包含TreeSet的元素內部排序的

  Java代碼

  public static void main(String[] args) {

  ArrayList<String> list = new ArrayList<String>();

  HashMap<ObjectObject> hash = new HashMap<ObjectObject>();

  TreeMap<ObjectObject> treeMap = new TreeMap<ObjectObject>();

  listadd(a);

  listadd(b);

  listadd(c);

  hashput( );

  hashput( );

  hashput( );

  hashput( );

  hashput( );

  hashput( );

  treeMapput( );

  treeMapput( );

  treeMapput( );

  treeMapput( );

  treeMapput( );

  treeMapput( );

  //list遍歷

  for(String m: list){

  Systemoutprintln(m);

  }

  // hashmap entrySet() 遍歷

  for(MapEntry<ObjectObject> m: hashentrySet()){

  Systemoutprintln(mgetKey()++mgetValue());

  }

  //hashmap keySet() 遍歷

  for(Object m: hashkeySet()){

  Systemoutprintln(m++hashget(m));

  }

  // treemap keySet()遍歷

  for(Object m: treeMapkeySet()){

  Systemoutprintln(m++treeMapget(m));

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26083.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.