天天看點

java中map的集中周遊方式

  • 樣例

    Map<String,String> map = new HashMap<String,String>();

    map.put(“寶寶”, “兒童”);

    map.put(“媽媽”, “成人”);

  • 1.最常用的周遊方式

    for(Map.Entry<String, String> entry : map.entrySet()){

    String mapKey = entry.getKey();

    String mapValue = entry.getValue();

    System.out.println(mapKey+":"+mapValue);

    }

  • 2.單獨周遊key或value
  • //key

    for(String key : map.keySet()){

    System.out.println(key);

    }

  • //value

    for(String value : map.values()){

    System.out.println(value);

    }

  • 3.通過Iterator周遊

    Iterator<Entry<String, String>> entries = map.entrySet().iterator();

    while(entries.hasNext()){

    Entry<String, String> entry = entries.next();

    String key = entry.getKey();

    String value = entry.getValue();

    System.out.println(key+":"+value);

    }

  • 4.不推薦

    for(String key : map.keySet()){

    String value = map.get(key);

    System.out.println(key+":"+value);

    }

繼續閱讀