(Java) HashMap 정리

HashMap이란 Map인터페이스의 한종류로써 Key와 Value 값으로 데이터를 저장하는 형태를 가지고 있습니다.
그러면 가만, Map이란 녀석을 무엇일까요? Map이란 놈은 키(Key) , 값(Value) 을 하나의 쌍으로 묶어서 저장하는 컬렉션 클래스들을 구현하는 데 사용 되는 녀석 입니다. 쉽게 말해 key, value 값으로 저장하는 List 형태의 조상이라고 생각 하시면 됩니다.


Map에 종류에는 Hashtable, HashMap, LinkedHashMap, SortedMap, TreeMap 등이 있습니다. 역시 이들 객체들 또한 key, value로 데이터를 저장하게 됩니다. 그 중에서 오늘은 HashMap에 대해서 다뤄 볼껀데요. HashMap또한 Map인터페이스를 구현한 녀석이기 때문에 Map의 속성을 모두 가지고 있고, 저장 방식 또한 동일 합니다. 그리고 해싱(hashing)이란 검색 방법을 사용하기 때문에 많은 양의 데이터를 검색하는데 있어서 뛰어난 성능을 보여줍니다.

HashMap에서 한가지 주의 하실 점이 map에 데이터를 등록할 때 , key값은 중복이 되지 않고 , value값은 중복이 허용된다는 점입니다. 예를들어,

map.put("사자","스피트90");
map.put("곰","힘100");
map.put("사자","힘80");
(최종 사자는 힘 80으로 저장된다)


public class TestHashMap {

public static void main(String[] args) {
                   // HashMap에 Data 넣기 (Key , Value) 형태  
HashMap<String , Integer> map = new HashMap<String , Integer>();
map.put("김태희", new Integer(90));
map.put("전혜빈", new Integer(80));
map.put("유인나", new Integer(100));
map.put("아이유", new Integer(90));
  // HashMap에 포함된 Key 중에 "유인나"라는 키를 가질 경우 true 리턴 (없을 경우 false) 
if(map.containsKey("유인나")){
System.out.println("유인나 최고");
}
 // HashMap에 포함된 Key , Value를 Set에 담고 iterator에 값을 Set 정보를 담아 준다.  
Set<Entry<String, Integer>> set = map.entrySet();
Iterator<Entry<String, Integer>> it = set.iterator();
 // HashMap에 포함된 key, value 값을 호출 한다. 
while (it.hasNext()) {
Map.Entry<String, Integer> e = (Map.Entry<String, Integer>)it.next();
System.out.println("이름 : " + e.getKey() + ", 점수 : " + e.getValue());
}
 // Map에서 저장된 Key들을 가져올 Set을 만든다.  
Set<String> set2 = map.keySet();
System.out.println("참가자 명단 : " + set2);
// Map에 저장된 value값들 Collection<Interger> 형태로 얻어 오고 iterator에 담는다.    Iterator<Integer> it2;
Collection<Integer> values = map.values();
it2 = values.iterator();
int total = 0;
while (it2.hasNext()) {
Integer i = (Integer)it2.next();
total += i.intValue();
}

 
// 결과 출력  
System.out.println("총점 : " + total);
System.out.println("평균 : " + (float)total/set.size());
System.out.println("최고점수 : " + Collections.max(values));
System.out.println("최저점수 : " + Collections.min(values));
}
}
 

참고사이트: http://arabiannight.tistory.com/entry/%EC%9E%90%EB%B0%94Java-%EC%9E%90%EB%B0%94-HashMap-%EC%9D%B4%EB%9E%80

댓글

이 블로그의 인기 게시물

(네트워크)폴링방식 vs 롱 폴링방식

(ElasticSearch) 결과에서 순서 정렬

(18장) WebSocekt과 STOMP를 사용하여 메시징하기