HashMap 종류

최지혜·2022년 11월 14일
0

java

목록 보기
20/33

Map
Iterator Class를 사용하여 데이터 꺼낼 때 유용

1. HashMap

일반적으로 가장 많이 사용하는 Map 객체이다.
속도가 빠른 대신 정렬순서는 알 수 없다.

public static void main(String[] args) {
    
    Map<String, String> map = new HashMap<String, String>();
    
    map.put("1", "111");
    map.put("A", "AAA");
    map.put("a", "aaa");
    map.put("가", "가가가");
    map.put("나", "나나나");
    map.put("b", "bbb");
    map.put("B", "BBB");
    map.put("2", "222");
    
    Iterator iterator = map.keySet().iterator();
    
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        System.out.println(key + " : " + map.get(key));
    }
}
<출력>
1
2
3
4
5
6
7
8
가 : 가가가
1 : 111
A : AAA
a : aaa
b : bbb
B : BBB
2 : 222
나 : 나나나

2. TreeMap

숫자 → 영어 대문자 → 영어 소문자 → 한글 순으로 정렬

public static void main(String[] args) {
    
    Map<String, String> map = new TreeMap<String, String>();
    
    map.put("1", "111");
    map.put("A", "AAA");
    map.put("a", "aaa");
    map.put("가", "가가가");
    map.put("나", "나나나");
    map.put("b", "bbb");
    map.put("B", "BBB");
    map.put("2", "222");
    
    Iterator iterator = map.keySet().iterator();
    
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        System.out.println(key + " : " + map.get(key));
    }
}
<출력>
1
2
3
4
5
6
7
8
1 : 111
2 : 222
A : AAA
B : BBB
a : aaa
b : bbb
가 : 가가가
나 : 나나나

3. LinkedHashMap

데이터를 넣은 순서대로 꺼냄

public static void main(String[] args) {
    
    Map<String, String> map = new LinkedHashMap<String, String>();
    
    map.put("1", "111");
    map.put("A", "AAA");
    map.put("a", "aaa");
    map.put("가", "가가가");
    map.put("나", "나나나");
    map.put("b", "bbb");
    map.put("B", "BBB");
    map.put("2", "222");
    
    Iterator iterator = map.keySet().iterator();
    
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        System.out.println(key + " : " + map.get(key));
    }
}
<출력>
1
2
3
4
5
6
7
8
1 : 111
A : AAA
a : aaa
가 : 가가가
나 : 나나나
b : bbb
B : BBB
2 : 222
profile
매일 성장하는 개발자

0개의 댓글