Javaexamples-collection-iterate

提供:Dev Guides
移動先:案内検索

Javaの例-HashMapを反復処理する

問題の説明

HashMapの要素を反復処理する方法は?

溶液

次の例では、Collectionクラスのiteratorメソッドを使用して、HashMapを反復処理します。

import java.util.*;

public class Main {
   public static void main(String[] args) {
      HashMap< String, String> hMap = new HashMap< String, String>();
      hMap.put("1", "1st");
      hMap.put("2", "2nd");
      hMap.put("3", "3rd");
      Collection cl = hMap.values();
      Iterator itr = cl.iterator();

      while (itr.hasNext()) {
         System.out.println(itr.next());
      }
   }
}

結果

上記のコードサンプルは、次の結果を生成します。

1st
2nd
3rd