프로그래밍 언어/JAVA(자바)

[자바/java] Map, HashMap - key, value 값 가져오기(feat. Set, Iterator)

냠냠:) 2020. 9. 3. 04:40

HashMap을 정리한 내용은 tosuccess.tistory.com/138 여기를 참고하세요!


HashMap 데이터를 다루기 좋은 연산 방법을 몇가지 정리했습니다.

 

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
    public static void main(String[] args) {
        HashMap<StringString> hm = new HashMap<StringString>();
        
        hm.put("안녕""하세요");
        hm.put("식사""하셨나요?");
        hm.put("안녕히""계세요");
        
        //keySet을 이용한 방법
        Iterator<String> iter = hm.keySet().iterator();
        while(iter.hasNext()) {
            String key = iter.next();
            System.out.println(key);
        }
        //안녕, 안녕히, 식사
        
        
        
        //keySet을 이용한 방법2
        for(String key : hm.keySet()) {
            System.out.println(key);
        }
        ////안녕, 안녕히, 식사
        
        
        
        //Entry를 이용한 방법
        Set set = hm.entrySet();
        Iterator iter2 = set.iterator();
        while(iter2.hasNext()) {
            Entry<StringString> entry = (Entry)iter2.next();
            System.out.println((String)entry.getKey()+" "+(String)entry.getValue());
        } 
        //안녕히 계세요,  안녕 하세요, 식사 하셨나요?
        
        
        
        
        //Entry를 이용한 방법2
        for(Entry<String,String> entry : hm.entrySet()) {
            System.out.println(entry.getKey()+" "+ entry.getValue());
        }
        //안녕히 계세요,  안녕 하세요, 식사 하셨나요?
    }
cs

 

반응형