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学習メモ⑥ HashMap

0
Last updated at Posted at 2026-05-30

HashMapと配列

JavaのHashMapと配列の違いは下記の通り。

項目 配列(Array) HashMap
要素の指定方法 インデックス(0, 1, 2...) キー(名前)
用途 同じ種類のデータを順番に管理 関連する情報をセットで管理
イメージ 「○番目の値」 「名前 → 値」
Java の例 int[] nums = {100, 200, 300}; HashMap<String, Integer>

HashMapはimportが必要

import java.util.HashMap;  //これが必要

public class Main {
    public static void main(String[] args){
        HashMap<String, Integer> scores = new HashMap<>();
        
        scores.put("国語", 80);
        scores.put("数学", 95);
        scores.put("英語", 88);        
    }
}

ポイント

  • HashMap<String, Integer> ⇒ <キー,値>
  • <> ⇒ ジェネリクスという
  • ジェネリクスにはintのような基本(プリミティブ)型は使えないため
    ラッパークラス【Integer】を使う

値の格納と取得

import java.util.HashMap;  //これが必要

public class Main {
    public static void main(String[] args){
        HashMap<String, Integer> items = new HashMap<>();

        //格納
        items.put("apple", 100);
        items.put("banana", 200);

        //取得
        System.out.println(items.get("apple"));
        System.out.println(items.get("banana"));
    }
}

ポイント

  • put(A, B) ⇒AにBを紐づけて格納する(再度同じキーでputすると上書きされる)
  • get("apple") ⇒appleに紐づいた値を取得する(存在しないキーでget()すると、nullが返され)

存在しないキーの場合にデフォルト値を返したい getOrDefault() メソッド

int price = priceMap.getOrDefault("メロン", 0);
System.out.println(price);  // 0(「メロン」がないのでデフォルト値が返る)

キーの存在確認 containsKey()

キーが存在するかを確認するには containsKey()
System.out.println(priceMap.containsKey("メロン"));    // false

値が存在するかを確認するには containsValue()
System.out.println(priceMap.containsValue(100));        // true

要素の削除 remove()

priceMap.remove("みかん");
System.out.println(priceMap);  // {りんご=150, ぶどう=300}

HashMapのループ

エントリーを使ったループ
import java.util.HashMap;
import java.util.Map;

// ...

for (Map.Entry<String, Integer> entry : priceMap.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue() + "円");
}

ポイント
entrySet() を使うと、キーと値のペア(エントリー)を直接取得できる
Map.Entry を使うには import java.util.Map; が必要
entry.getKey() でキーを、entry.getValue() で値を取得

キーだけを取得してループ

HashMap<String, Integer> priceMap = new HashMap<>();
priceMap.put("りんご", 150);
priceMap.put("みかん", 100);
priceMap.put("ぶどう", 300);

for (String key : priceMap.keySet()) {
    System.out.println(key + ": " + priceMap.get(key) + "円");
}

ポイント

  • var(型推論) ⇒変数の型を自動的に判定(短く書ける)
    varを使わない場合 ⇒Map.Entry<String, Integer> entry

HashMapの要素を表示

import java.util.HashMap;  //必ず必要

public class Main{
    public static void main(String[] args){
        HashMap<String, Integer> items = new HashMap<>();
        items.put("apple", 100);
        items.put("banana", 200);
        items.put("orange", 300);

        for (var entry : items.entrySet()){
            System.out.println(entry.getKey() + ":" + entry.getValue() + "円");
        }
    }
}
banana:200円
orange:300円
apple:100円

ポイント

  • entrySet() ⇒キーと値のペアを取得
  • HashMapは要素の順序が保証されない

商品名を表示する(メソッドの引数としてHashMapを渡す)

import java.util.HashMap;  //必ず必要

public class Main{
    public static void cashier(HashMap<String, Integer> items){
        for (var entry : items.entrySet()){
            System.out.println(entry.getKey() + "が1点");
        }
    }
    public static void main(String[] args){
        HashMap<String, Integer> items = new HashMap<>();
        items.put("apple", 100);
        items.put("banana", 200);
        items.put("orange", 300);

        cashier(items);
    }
}
結果
bananaが1点
orangeが1点
appleが1点

2人目まで表示

import java.util.HashMap;  //必ず必要

public class Main{
    public static void cashier(HashMap<String, Integer> items){
        int total = 0;
        for (var entry : items.entrySet()){
            System.out.println(entry.getKey() + "が1点");
            total += entry.getValue();
        }
        System.out.println("合計金額は" + (int)(total * 1.1) + "円です");
    }
    public static void main(String[] args){
        HashMap<String, Integer> items1 = new HashMap<>();
        items1.put("apple", 100);
        items1.put("banana", 200);
        items1.put("orange", 300);
        cashier(items1);

        System.out.println("---次のお客様---");

        HashMap<String, Integer> items2 = new HashMap<>();
        items2.put("milk", 150);
        items2.put("bread", 200);
        items2.put("egg", 250);
        cashier(items2);
    }
}
結果
bananaが1点
orangeが1点
appleが1点
合計金額は660円です
---次のお客様---
breadが1点
eggが1点
milkが1点
合計金額は660円です

まとめ
・importを必ず書く
・ジェネリクス<>にintではなく、Integerを使う
・getKey()とgetValue()の使い分けに注意
・putで格納し、getKey()、getValue()で値を取得
・putメソッドのキーと値を逆に書いてしまうとコンパイルエラーになる
・entrySet() と拡張for文を使ってHashMapの全要素をループ処理できる

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?