HashMapからkeyとvalueをプリントする2種類の方法

下記を参考に

https://qiita.com/Jazuma/items/893ff79799325c7bd0d3


import java.util.*;


public class Main {
    public static void main(String[] args) {
        // 自分の得意な言語で
        // Let's チャレンジ!!
        Scanner sc = new Scanner(System.in);
        
        int company = sc.nextInt();
        int times = sc.nextInt();
        
        
        LinkedHashMap<String, Acount> acounts = new LinkedHashMap<>();
    
        for (int i = 0; i < company; i++) {
            String name = sc.next();
            String pass = sc.next();
            int amount = sc.nextInt();
            acounts.put(name, new Acount(name, pass, amount));
        }
        
        for (int i = 0; i < times; i++) {
            String name = sc.next();
            String pass = sc.next();
            int payment = sc.nextInt();
            
            Acount acount = acounts.get(name);
            if(acount != null){
                if(pass.equals(acount.getPass())) {
                    if (acount.getAmount() >= payment) {
                        int amount =acount.getAmount() - payment;
                        acount.setAmount(amount);
                    } else {
                        acount.setAmount(0);
                    }
                }
            }
                
        }
        
        for(Map.Entry<String, Acount> entry : acounts.entrySet()) {
           System.out.println(entry.getValue().getName() + " " +entry.getValue().getAmount());
        }
    }

}
    
    
class Acount {
    String name;
    String pass;
    int amount;
    
    Acount(String name, String pass, int amount) {
        this.name = name;
        this.pass = pass;
        this.amount = amount;
    }
    
    public String getName() {
        return name;
    }
    
    public String getPass() {
        return pass;
    }
    
    public int getAmount() {
        return amount;
    }
    
    public void setAmount(int amount) {
        this.amount = amount;
    }
}


import java.util.*;
import java.util.Map.Entry;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        
        hashMap.put("A", "Alice");
        hashMap.put("B", "Bob");
        hashMap.put("C", "Char");
        
        for (Entry<String, String> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }  //←これが①
        
        hashMap.forEach((key, value) -> System.out.println(key + ":" + value)); //これが②

    }
}

拡張forを使う場合

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

getKey と getValueを使う

cgの見解

メリット:

  • エントリーの明示的な操作: Map.Entryオブジェクトを使って、キーと値に対して操作を行えるので、必要に応じてエントリー全体を操作したい場合に便利です。
  • 可読性: 明確にエントリーを扱うことがわかるため、読みやすさの点では優れています。getKey()getValue()メソッドを使っているため、どの要素がキーで、どの要素が値かを理解しやすいです。

デメリット:

  • 冗長さ: シンプルな操作に対して少しコードが長くなりがちです。特に、キーと値の単純な出力だけを行う場合には少し無駄があるように感じるかもしれません。

forEachを使う場合

hashMap.forEach((key, value) -> System.out.println(key + ":" + value));

cgの見解

メリット:

  • 簡潔さ: forEachメソッドを使用することで、ラムダ式を使った簡潔なコードが書けます。キーと値を直接操作できるため、シンプルな処理には最適です。
  • 可読性: 短いコードで目的が明確な場合、コード全体がすっきりしていて見やすいです。

デメリット:

  • エントリー全体の操作が難しい: Map.Entryとして扱わないため、キーと値それぞれに対する簡単な処理に向いていますが、エントリー全体を操作したい場合には不向きです。

CGの結論

  • シンプルなキーと値の操作であれば、forEachメソッド(ラムダ式)を使う方がより簡潔で良い選択です。
  • エントリー全体を操作する場合や、特定の要件でキーと値に対して個別に高度な操作が必要な場合は、entrySet()を使ったfor-eachループが適しています。

単にkey:valueのペアをプリントするだけであれば、forEachメソッドを使う方が簡潔でおすすめです。


投稿日

カテゴリー:

, , , , ,

投稿者: