Javaサンプルコード辞典

Map - Mapから全てのキーと値のセットを取得する

Mapから全てのキーと値のセットを取得するサンプルコードです。

Mapから全てのキーと値のセットを取得するためにはまず、entrySet()メソッドで、キーと値のセットを格納するSet型のコレクションを取得します。そして、取得したコレクションから反復子(Iterator)を使用して、キーと値のセットを持つMap.Entry型のオブジェクトを取得します。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//Mapから全てのキーと値のセットを取得する
public class GetAllMap {

      public static void main(String[] args) {
            
            //Mapを生成する
            Map<Integer, String> map = new HashMap<Integer, String>();
            
            //Mapに値をキーと値のエントリを追加する
            map.put(new Integer(1), "A");
            map.put(new Integer(2), "B");
            map.put(new Integer(3), "C");
            map.put(new Integer(4), "D");
            map.put(new Integer(5), "E");
            
            //Mapから全てのキーと値のエントリをSet型のコレクションとして取得する
            Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
            
            //キーと値のコレクションの反復子を取得する
            Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
            
            //次の要素がまだ存在する場合はtrueが返される
            while(it.hasNext())
            {
                  //キーと値をセットを持つ、Map.Entry型のオブジェクトを取得する
                  Map.Entry<Integer, String> entry = it.next();
                  
                  //Map.Entry型のオブジェクトからキーを取得する
                  Integer key = entry.getKey();
                  //Map.Entry型のオブジェクトから値を取得する
                  String value = entry.getValue();
                  
                  //標準出力に表示する
                  System.out.format("%d : %s \r\n", key,value);
            }
      }
}

(2007年11月3日)  

 ちょっと一休み. Javaキーワード並び替えゲーム

画面に表示される文字列を並び替えるとJavaに関連するキーワードになります。ヒントをたよりに並び替えを行ってエンターを押してください。 ユーザ登録をしてログインするとランキングに参加できます。
Flex Tips

DWRでリッチなWebページを作る!

Java Tips  java.io 編

Java Tips  java.lang 編