0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】3分で読めるMapについて

Posted at

Mapとは

キー(key)と値(value)をセットで保存するインタフェース

Map<String, Integer> map = new HashMap<>();
map.put("apple",100);
map.put("banana",200);
System.out.println("apple"); // 100

Mapの特徴

  1. keyは一意(重複しない)
  2. valueは重複してもよい

HashMapとは

Mapインタフェースの実装クラス
高速な検索・追加・削除が可能なデータ構造

  • 順序の保持はしない
  • keyにnullをひとつだけ設定できる
  • 値にnullを複数設定できる
  • スレッドセーフではない(並行処理で問題が発生する可能性あり)

Mapで使用するメソッド

①要素の追加 map.put("key",value);

Map<String, String> map = new HashMap<>();
map.put("name", "Taro");
map.put("city", "Tokyo");
map.put("job", "Teacher")

② 要素の取得 map.get("key");

System.out.println("name:" + map.get("name")); // Taro

③ 要素の削除 map.remove("key");

map.remove("city");

④ キーの存在確認 map.containsKey("key");

System.out.println(map.containsKey("name")); // true
System.out.println(map.containsKey("city")); // false

⑤ 値の存在確認 map.containsValue(value);

System.out.println(map.containsValue("Taro")); // true
System.out.println(map.containsValue("Tokyo")); // false

⑥ マップの要素数を取得 map.size();

System.out.println(map.size()); // 2

⑦ 全てのキーを取得 map.keySet();

System.out.println(map.keySet()); // [name, job] 

⑧ 全ての値を取得 map.values();

System.out.println(map.values()); // [Taro, Teacher] 

⑨ 全てのエントリ取得 map.entrySet();

System.out.println(map.entrySet()); // [name:"Taro", job:"Teacher"] 

記事作成時間:25分

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?