03.08 Java HashMap遍歷的四種方式

通過Map.values()遍歷所有的value,不能遍歷key

<code> public class TestDemo{
     public static void main(String[] args) {
         HashMap<string>  hashMap = new HashMap<>();
         hashMap.put("name","Jack");
         hashMap.put("sex","boy");
 
         // 通過Map.values()遍歷所有的value,不能遍歷key
         for (String v : hashMap.values()) {
             System.out.println("value=" + v);
        }
  }
  }/<string>/<code>

執行結果如下:

<code> value=boy
 value=Jack/<code>

通過獲取HashMap中所有的key按照key來遍歷

<code> public class TestDemo{
     public static void main(String[] args) {
         HashMap<string>  hashMap = new HashMap<>();
         hashMap.put("name","Jack");
         hashMap.put("sex","boy");
 
         // 通過獲取HashMap中所有的key按照key來遍歷
         for (String key : hashMap.keySet()) {
             //得到每個key多對用value的值
             String value = hashMap.get(key);
             System.out.println("key="+ key +"; value="+value);
        }
  }
  }/<string>/<code>

執行結果如下:

<code> key=sex; value=boy
 key=name; value=Jack/<code>


通過Map.entrySet使用iterator遍歷key和value

<code> public class TestDemo{
     public static void main(String[] args) {
         HashMap<string>  hashMap = new HashMap<>();
         hashMap.put("name","Jack");
         hashMap.put("sex","boy");
 
         // 通過Map.entrySet使用iterator遍歷key和value
         Iterator<map.entry>> entryIterator =
             hashMap.entrySet().iterator();
         while (entryIterator.hasNext()) {
             Map.Entry<string> entry = entryIterator.next();
             System.out.println("key=" + entry.getKey() + "; value= " +
                                entry.getValue());
        }
    }
 }/<string>/<map.entry>/<string>/<code>

執行結果如下:

<code> key=sex; value=boy
 key=name; value=Jack/<code>


通過Map.entrySet遍歷key和value

<code> public class TestDemo{
     public static void main(String[] args) {
         HashMap<string>  hashMap = new HashMap<>();
         hashMap.put("name","Jack");
         hashMap.put("sex","boy");
 
         // 通過Map.entrySet遍歷key和value,[推薦]
         for (Map.Entry<string> stringEntry : hashMap.entrySet()){
             System.out.println("key=" + stringEntry.getKey() + "; value="
                                + stringEntry.getValue());
        }
    }
 }/<string>/<string>/<code>

執行結果如下:

<code> key=sex; value=boy
 key=name; value=Jack/<code>



分享到:


相關文章: