反復処理を使用した最大値の検索
Map内の最大値を見つける方法の1つは、すべてのエントリを反復処理し、これまでに見つかった最大値を追跡することです。このアプローチは、あらゆるMapの実装で機能します。
Map.Entryとは何か?
Map.Entry
は、Map内のキーと値のペアを表すインターフェースです。このインターフェースには、ペア内のキーと値の両方にアクセスするためのメソッドが用意されています。
反復アプローチの実装
反復処理を使用して最大のコース価格を見つけるように、Javaプログラムを変更しましょう。
- WebIDEで
MaxValueInMap.java
ファイルを開きます。
- 既存のコードを以下のコードに置き換えます。
import java.util.*;
public class MaxValueInMap {
public static void main(String args[]) {
// Create a HashMap to store course prices
Map<String, Integer> coursePrices = new HashMap<>();
// Variable to store the entry with maximum price
Map.Entry<String, Integer> maxEntry = null;
// Add key-value pairs to the map
coursePrices.put("Java", 5000);
coursePrices.put("Python", 3000);
coursePrices.put("CPP", 4000);
coursePrices.put("Android", 8000);
System.out.println("Course price map: " + coursePrices);
// Iterate through each entry in the map
for (Map.Entry<String, Integer> entry : coursePrices.entrySet()) {
// If maxEntry is null OR current entry's value is greater than maxEntry's value
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
// Print the maximum price and its corresponding course
System.out.println("Course with maximum price: " + maxEntry.getKey());
System.out.println("Maximum price: " + maxEntry.getValue());
}
}
- ファイルを保存します。
- 以下のコマンドでプログラムを実行します。
javac MaxValueInMap.java && java MaxValueInMap
以下のような出力が表示されるはずです。
Course price map: {Java=5000, CPP=4000, Android=8000, Python=3000}
Course with maximum price: Android
Maximum price: 8000
反復処理の仕組み
- 最初に
maxEntry
変数を null
に設定します。
entrySet()
メソッドを使用して、Map内の各エントリを反復処理します。
- 各エントリについて、その値を現在の最大値と比較します。
- 現在のエントリの値がより大きい場合、または
maxEntry
がまだ null
の場合、maxEntry
を更新します。
- 反復処理が完了すると、
maxEntry
には最大値を持つエントリが格納されます。
このアプローチは、最大エントリのキーと値の両方が必要な場合に便利です。