Skip to content

Instantly share code, notes, and snippets.

@teachingprogramming
Last active May 15, 2018 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teachingprogramming/6eff80f7c69535fba6d24c0ce01e5463 to your computer and use it in GitHub Desktop.
Save teachingprogramming/6eff80f7c69535fba6d24c0ce01e5463 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
public class MapSample {
public static void main(String[] args) {
// キーが文字列、値が文字列のマップを作成(インスタンス化)
Map<String, String> addressBook = new HashMap<String, String>();
// キーと値をペアで登録する。
addressBook.put("taro", "taro@example.com");
addressBook.put("jiro", "jiro@example.jp");
addressBook.put("hanako", "hanako@example.net");
// キーから値を取得する
String name = "taro";
String email = addressBook.get(name);
System.out.println(name + "のメールアドレスは" + email + "です。");
// キーが同じ場合は値が上書きされる。
addressBook.put("taro", "taro@example.co.jp");
System.out.println("taroのメールアドレス: " + addressBook.get("taro"));
// 削除する
addressBook.remove("taro");
String email2 = addressBook.get("taro");
if (email2 == null) {
System.out.println("taroは登録されていません。");
}
// キーが登録されているかチェックする
boolean exist = addressBook.containsKey("jiro");
if (exist) {
System.out.println("jiroは登録されている。");
} else {
System.out.println("jiroは登録されていない。");
}
// キーを全て取得、表示する。
for (String k : addressBook.keySet()) {
System.out.println(k);
}
// キーと値を全て取得、表示する。
for (String k : addressBook.keySet()) {
String v = addressBook.get(k);
System.out.println(k + ", " + v);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment