JAVA

[Java] HashMap에서 최대값/최소값 key, value 찾기

jjuya 개발 기록 2024. 7. 20. 20:34

key기준 최대값 / 최소값 찾기

import java.util.Collections;
import java.util.HashMap;
import java.util.Map; 
public class HashMapMax {    
    public static void main(String[] args) {         
        
        // HashMap 준비        
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        
        map.put(1, 5);        
        map.put(2, 70);        
        map.put(3, 50);  
        
        // Max Key        
        Integer maxKey = Collections.max(map.keySet());         
        
        // Min Key        
        Integer minKey = Collections.min(map.keySet());         
        
        // 결과 출력        
        System.out.println(maxKey); // 3        
        System.out.println(minKey); // 1    
    }
}
  • Integer maxKey = Collections.max(map.keySet());
    • Collections.max()는 전달받은 Set에서 가장 큰 값을 찾아서 리턴
  • Integer minKey = Collections.min(map.keySet()); 
    • Collections.min()은 전달받은 Set에서 가장 작은 값을 찾아서 리턴

 

value 기준 최대값 / 최소값 찾기

import java.util.Collections;
import java.util.HashMap;
import java.util.Map; 
public class HashMapMax {    
    public static void main(String[] args) {
        // HashMap 준비
         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
         map.put(1, 5);
         map.put(2, 70);
         map.put(3, 50);         
        // Max Value
         Integer maxValue = Collections.max(map.values());         
        // Min Value
         Integer minValue = Collections.min(map.values());         
        // 결과 출력
         System.out.println(maxValue); // 70        
         System.out.println(minValue); // 5    
    }
}