MapIterator
by 핫도구반응형
HashMap의 순차처리(Iterator, Entry)
HashMap의 주요 메서드( Set type으로 return)
- entrySet() : key + value를 Entry Type으로 묶어 집합으로 반환
- keySet() : key값들만 집합으로 반환
- values() : value들만 집합으로 반환
여기서 HashMap을 정의 → 초기화 → 순차처리(key와 value값을집합으로 만들어주기) → 이후 Iterator로 반복자로 만들어주기 → key, value의 값을 구분하기 위해 Entry 객체를 사용해야하는데 Entry객체는 Map의 inner class이므로 Map.Entry로 접근한다.
Map<String, Integer> hm = new HashMap<>();
hm.put("아아", 5);
hm.put("라떼", 6);
hm.put("뜨아", 4);
hm.put("카푸치노", 8);
hm.put("에이드", 10);
System.out.println("hm => " + hm); // {카푸치노=8, 라떼=6, 에이드=10, 아아=5, 뜨아=4}
Set<?> set = hm.entrySet();
System.out.println(set);
Iterator<?> iSet = set.iterator();
while (iSet.hasNext()) {
// System.out.println("iSet.next() => "+iSet.next());
// key, value로 구분해야한다.
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iSet.next();
// instance entry를 통해 key와 value에 접근할 수 있게 된다.
System.out.printf("Entry : key = %s, value = %d \n", entry.getKey(), entry.getValue());
}
//Entry : key = 카푸치노, value = 8
//Entry : key = 라떼, value = 6
//Entry : key = 에이드, value = 10
//Entry : key = 아아, value = 5
//Entry : key = 뜨아, value = 4
이와 같이 접근을 해도 되고 keySet(), values()로 각각 접근해도 된다.
각각 정의한 후 반복자(iterator)로 재정의 한 후 정의하기
Set<?> set = hm.keySet();
System.out.println("keySet => " + set); // [카푸치노, 라떼, 에이드, 아아, 뜨아]
Iterator<?> iSet = set.iterator();
while (iSet.hasNext()) {
String hmKey = (String) iSet.next();
System.out.printf("while문 key = %s, value = %d \n", hmKey, hm.get(hmKey));
}
//while문 key = 카푸치노, value = 8
//while문 key = 라떼, value = 6
//while문 key = 에이드, value = 10
//while문 key = 아아, value = 5
//while문 key = 뜨아, value = 4
for (String s : hm.keySet()) {
System.out.printf("for문 key = %s, value = %d \n", s, hm.get(s));
}
//for문 key = 카푸치노, value = 8
//for문 key = 라떼, value = 6
//for문 key = 에이드, value = 10
//for문 key = 아아, value = 5
//for문 key = 뜨아, value = 4
//values() : value들만 Set으로 만들어 총 합계, 평균을 출력할 수 있따.
// 또한 Collections를 활용해 최대값, 최솟값을 도출할 수 있다.
Collection<Integer> cv = hm.values();
iSet = cv.iterator();
int sum = 0;
while (iSet.hasNext()) {
sum += (Integer) iSet.next();
}
System.out.println("총 합계 = " + sum); // 33
System.out.println("평균 = " + sum / hm.size()); // 6
System.out.println("최고값 = " + Collections.max(cv)); // 10
System.out.println("최소값 = " + Collections.min(cv)); // 4반응형
'JAVA > OLD' 카테고리의 다른 글
| JDBC (0) | 2024.08.08 |
|---|---|
| Properties (0) | 2024.07.29 |
| Map(HashMap, TreeMap, LinkedHashMap) (0) | 2024.07.29 |
| 다양한 집합(합집합, 교집합, 차집합, 부분집합) (0) | 2024.07.29 |
| Set(HashSet, TreeSet, LinkedHashSet) (0) | 2024.07.29 |
블로그의 정보
AquaMan
핫도구