ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
| この記事の要点 |
|
作り方と基本操作
Map<String, Integer> scores = new HashMap<>();
scores.put("math", 80);
scores.put("english", 70);
scores.put("math", 90); // 同じキーなら上書き(戻り値は前の値 80)
System.out.println(scores.get("math")); // 90
System.out.println(scores.get("science")); // null
System.out.println(scores.getOrDefault("science", 0)); // 0
System.out.println(scores.containsKey("math")); // true
System.out.println(scores.containsValue(70)); // true
System.out.println(scores.size()); // 2
System.out.println(scores.isEmpty()); // false
scores.remove("english");
scores.clear();
// 変更できない Map を作る(Java 9 以降)
Map<String, Integer> fixed = Map.of("math", 80, "english", 70);
// fixed.put("x", 1); // UnsupportedOperationException
// 10 組を超えるときや順序を保ちたいとき
Map<String, Integer> fixed2 = Map.ofEntries(
Map.entry("math", 80),
Map.entry("english", 70));
// 既存の Map から作る
Map<String, Integer> copy = new HashMap<>(scores);
Map<String, Integer> readOnly = Collections.unmodifiableMap(scores);
実装クラスの使い分け
| クラス | 順序 | 速度 | null キー | 使う場面 |
|---|---|---|---|---|
HashMap | 不定 | O(1) | 1 個だけ可 | 既定 |
LinkedHashMap | 登録順 | O(1) | 1 個だけ可 | 順序を保ちたい / LRU キャッシュ |
TreeMap | キーの昇順 | O(log n) | 不可 | 並べ替えて持ちたい / 範囲検索 |
ConcurrentHashMap | 不定 | O(1) | 不可 | 複数スレッドから使う |
EnumMap | enum の定義順 | 非常に速い | 不可 | キーが enum のとき |
Hashtable | 不定 | 遅い | 不可 | 使わない(古い) |
Map<String, Integer> hash = new HashMap<>();
hash.put("c", 3); hash.put("a", 1); hash.put("b", 2);
System.out.println(hash); // {a=1, b=2, c=3} と出ることもあるが保証はない
Map<String, Integer> linked = new LinkedHashMap<>();
linked.put("c", 3); linked.put("a", 1); linked.put("b", 2);
System.out.println(linked); // {c=3, a=1, b=2} 登録順
Map<String, Integer> tree = new TreeMap<>(hash);
System.out.println(tree); // {a=1, b=2, c=3} キーの昇順
System.out.println(((TreeMap<String,Integer>) tree).firstKey()); // a
HashMap の並び順に依存したコードを書かないでください。要素数や JDK のバージョンで変わります。
キーの条件
public class UserKey {
private final int id;
public UserKey(int id) { this.id = id; }
}
Map<UserKey, String> map = new HashMap<>();
map.put(new UserKey(1), "田中");
System.out.println(map.get(new UserKey(1))); // null ← 見つからない
// equals と hashCode を実装すれば見つかる
public record UserKey(int id) {} // record なら自動生成される
Map<UserKey, String> map = new HashMap<>();
map.put(new UserKey(1), "田中");
System.out.println(map.get(new UserKey(1))); // 田中
キーに使うオブジェクトは、登録後に中身を変えてはいけません。hashCode() が変わると、入れたはずの値が二度と取り出せなくなります。record や final フィールドで不変にしてください。
集計に使う
List<String> words = List.of("a", "b", "a", "c", "a");
// 出現回数を数える(古い書き方)
Map<String, Integer> count = new HashMap<>();
for (String w : words) {
if (count.containsKey(w)) {
count.put(w, count.get(w) + 1);
} else {
count.put(w, 1);
}
}
// merge を使う
Map<String, Integer> count2 = new HashMap<>();
for (String w : words) {
count2.merge(w, 1, Integer::sum);
}
// getOrDefault を使う
count2.put("a", count2.getOrDefault("a", 0) + 1);
// キーごとにリストへ追加する
Map<String, List<String>> grouped = new HashMap<>();
for (String w : words) {
grouped.computeIfAbsent(w, k -> new ArrayList<>()).add(w);
}
// Stream で一気に
Map<String, Long> count3 = words.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
| メソッド | 働き |
|---|---|
putIfAbsent(k, v) | キーが無い(または null)ときだけ入れる |
computeIfAbsent(k, f) | 無ければ f で作って入れ、その値を返す |
computeIfPresent(k, f) | あるときだけ計算し直す |
compute(k, f) | 有無に関わらず計算する。null を返すと削除される |
merge(k, v, f) | 無ければ v、あれば f(既存, v) |
replaceAll(f) | すべての値を変換する |
走査する
Map<String, Integer> scores = Map.of("math", 80, "english", 70);
// キーと値を両方使う(最も効率が良い)
for (Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
// ラムダ
scores.forEach((k, v) -> System.out.println(k + ": " + v));
// キーだけ / 値だけ
for (String k : scores.keySet()) { }
for (Integer v : scores.values()) { }
// 走査しながら削除するときは Iterator を使う
Iterator<Map.Entry<String, Integer>> it = new HashMap<>(scores).entrySet().iterator();
while (it.hasNext()) {
if (it.next().getValue() < 75) it.remove();
}
// または
Map<String, Integer> m = new HashMap<>(scores);
m.entrySet().removeIf(e -> e.getValue() < 75);
拡張 for の中で put() や remove() を呼ぶと ConcurrentModificationException になります。取り出しの詳細は キーと値の取得 を参照してください。
null の扱い
Map<String, Integer> map = new HashMap<>();
map.put("a", null);
System.out.println(map.get("a")); // null
System.out.println(map.get("missing")); // null ← 区別できない
System.out.println(map.containsKey("a")); // true こちらで区別する
// アンボックス化で落ちる
// int n = map.get("missing"); // NullPointerException
int n = map.getOrDefault("missing", 0); // 安全
// Map.of は null を許さない
// Map.of("a", null); // NullPointerException
スレッドと性能
// 複数スレッドから触るなら ConcurrentHashMap
Map<String, Integer> safe = new ConcurrentHashMap<>();
safe.merge("a", 1, Integer::sum); // これ自体は原子的
// 件数が分かっているなら初期容量を指定する(再構築を避ける)
Map<String, Integer> big = new HashMap<>(10_000);
// LinkedHashMap で LRU キャッシュ
Map<String, String> lru = new LinkedHashMap<>(16, 0.75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<String, String> e) {
return size() > 100;
}
};
HashMap を複数スレッドから同時に更新すると、無限ループやデータの消失が起きます。共有するなら ConcurrentHashMap にしてください。
関連
ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
子ページ
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- 【django】ログイン 認証機能 2026-09-08 03:22:09
- MySQL ERROR 1063 Incorrect column specifier for column|原因と直し方 2026-09-08 03:11:09
- 【PHPエラー】Object of class stdClass could not be converted to string 2026-09-07 07:46:04
- Julia Genie ローカル開発サーバ起動完全ガイド 2026-09-07 07:46:04
- Wi-Fi とは|規格と世代(Wi-Fi 4〜7)・周波数帯・CSMA/CA・WPA3 NEW 2026-09-07 07:45:13
- set コマンドでシェルオプションと位置パラメータを操作 | bash 2026-09-07 07:45:13
- JPEG(.jpg/.jpeg)画像形式の完全ガイド — 仕様・マジックナンバー・他形式との比較・EXIF 2026-09-07 07:45:13
- UE5 Get Overlapping Actorsで特定クラスだけ処理|Class Filter・Cast To 2026-09-07 07:45:13
- Linuxで特定拡張子のファイルを再帰削除|find -deleteの安全手順 2026-09-07 07:45:13
- Django CBVでテンプレートに値を渡す|get_context_data・extra_context 2026-09-07 07:45:13
- Linuxで複数ファイルの文字列を一括置換|find・sed・xargsの安全手順 2026-09-07 07:45:13
- Laravelルートグループ|prefix・middleware・nameで一括管理 2026-09-07 07:45:13
- Linux whichコマンドの使い方|絶対パス取得とtype・command -vの違い 2026-09-07 07:45:13
- Linux catコマンドの使い方|行番号表示・複数ファイル連結 2026-09-07 07:45:13
- unable to execute 'gcc': No such file or directory 2026-09-07 07:45:13
コメントを削除してもよろしいでしょうか?