JAVA

HashMapを使う

HashMapを使って次のようなプログラムを書きます。

[c]
package TestPackage;

import java.util.HashMap;
import java.util.Map;

public class LinkedListTest6 {

/**
* @param args
*/
public static void main(String[] args) {

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

//要素の追加
map.put("test2", 100);
map.put("qqq", 67);
map.put("www", 34);
map.put("eee", 81);

System.out.println("map -> " + map);

//ここに、コレクションの操作を記述する

}

}

[/c]

実行結果は次のようなります。
[c]
map -> {qqq=67, www=34, test2=100, eee=81}
[/c]

「キー項目と値」のセットになっていることがわかります。
Hashmapはこのように、2つセットのものを、要素分、格納するコレクションと言えます。

次に、このコレクションを操作してみます。
「ここに、コレクションの操作を記述する」という箇所に次のようなプログラムを書いて見ます。

■キーと値を同時に取得する

[c]
for (Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
[/c]
実行結果は次のようになります。
[c]
qqq=>67
www=>34
test2=>100
eee=>81
[/c]

■キーを取得する
[c]
for (String name : map.keySet()){
System.out.println(name);
}
[/c]
実行結果は次のようになります。
[c]
qqq
www
test2
eee
[/c]

■値を取得する
[c]
for (Integer name : map.values()) {
System.out.println(name);
}
[/c]
実行結果は次のようになります。
[c]
67
34
100
81
[/c]

■キーと値を取得する
[c]
for (String name : map.keySet()) {
System.out.println(name + "->" + map.get(name));
}
[/c]
実行結果は次のようになります。
[c]
qqq->67
www->34
test2->100
eee->81
[/c]

■あるキーをもとに値を取得する
[c]
System.out.println(map.get("qqq"));
[/c]
実行結果は 「67」 になります。

これは2つ目の要素の値を取得してきていることがわかります。

コレクションの使い方は上記のほかにもまだまだ使い方があるので、別途追求しようと思います。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です