반복문을 사용하여 최대값 찾기
Map 에서 최대값을 찾는 한 가지 방법은 모든 항목을 반복하고 지금까지 발견된 최대값을 추적하는 것입니다. 이 접근 방식은 모든 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는 최대값을 가진 항목을 저장합니다.
이 접근 방식은 최대 항목의 키와 값 모두가 필요한 경우 유용합니다.