Dev.J

[JAVA] 문제 12-2 3개의 나라이름과 인구를 입력받아 HashMap에 저장 / 컬렉션(map) 본문

Solved

[JAVA] 문제 12-2 3개의 나라이름과 인구를 입력받아 HashMap에 저장 / 컬렉션(map)

JJ____ 2021. 9. 23. 14:46

 3개의 나라이름과 인구를 입력받아 HashMap에 저장하고. 가장 인구가 많은 나라를 검색하여 출력하는 프로그램을 완성하시오.

 map의 키값들을 가져와서(keySet() 을 이용) Iterator를 사용하여 제일 큰 값을 찾는다.

 

1) keySet()메소드로 Set컬렉션을 얻은 후, 반복자로 하나씩 get() 통해 값을 가져온다.

Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
    String key = it.next();
    System.out.println(String.format("키 : %s, 값 : %s", key, map.get(key)));
}

for (String key : map.keySet()) {
    System.out.println(String.format("키 : %s, 값 : %s", key, map.get(key)));
}

첫줄 코드에서 keySet()메소드를 호출하면 모든 key값이 Set 객체로 반환됨.
Set객체에 iterator() 메소드를 호출하면 key를 순회할 수 있는 Iterator이 반환됨.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.Iterator;
 
public class Assignment12_2 {
 
    public static void main(String[] args) {
        System.out.println("나라 이름과 인구를 3개 입력하세요. (예: Korea 5000)");
        HashMap<String,Integer> coun = new HashMap<String,Integer>();
        
        Scanner sc = new Scanner(System.in);
        String name1;
        int people1;
        String name2;
        int people2;
        String name3;
        int people3;
        
        System.out.println("1. 나라이름, 인구>>");
        name1 = sc.next();
        people1 = sc.nextInt();
        coun.put(name1 , people1);
        
        System.out.println("2. 나라이름, 인구>>");
        name2 = sc.next();
        people2 = sc.nextInt();
        coun.put(name2 , people2);
        
        System.out.println("3. 나라이름, 인구>>");
        name3 = sc.next();
        people3 = sc.nextInt();
        coun.put(name3 , people3);
        
        Set<String> keys = coun.keySet();
        Iterator<String> it = keys.iterator();
        
        int max = 0;            //가장 많은 인구수
        String max_coun = "";    //가장 많은 인구를 가진 나라
        
        while (it.hasNext()) {
         String key = it.next();
         int value = coun.get(key);        //해쉬맵명.get(key) == key에 해당하는 value를 구하는 메서드
         if(max < value) {
                 max = value;
                 max_coun = key;
             }            
        }    
        System.out.println("제일 인구가 많은 나라는 (" +max_coun+ ", "+max+")");
    }
}
cs

 

실행결과

나라 이름과 인구를 3개 입력하세요. (예: Korea 5000)
1. 나라이름, 인구>>
a 5
2. 나라이름, 인구>>
b 9
3. 나라이름, 인구>>
c 12
제일 인구가 많은 나라는 (c, 12)

728x90