HashMap이란

HashMap이란 Map인터페이스의 한종류로써 Key와 Value 값으로 데이터를 저장하는 형태이다.
키의 경우는 중복을 허용하지 않으며 Value의 경우는 중복을 허용한다.

또한, 순서가 유지되지 않는다. 순서 유지가 필요하다면 LinkedHashMap을 사용한다.

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a",1);
map.put("b",1);
map.put("c",3);
map.put("c",5);

System.out.println(map); // 결과값 : {a=1, b=1, c=5}

 

값은 중복이 허용되지만 키는 중복이 불가능 하기때문에 같은 키의 마지막 등록 된 값이 출력된다.

 

특정 key 값의 value 가져오기

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a",1);
map.put("b",1);
map.put("c",3);
map.put("c",5);

System.out.println(map.get("a")); // 결과값 : 1

get(key)를 사용해서 원하는 key의 value를 가져올 수 있다.

 

 

전체 key value 가져오기

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a",1);
map.put("b",1);
map.put("c",3);
map.put("d",5);

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

// 방법2
for( Map.Entry<String, String> elem : map.entrySet() ){
System.out.println( String.format("키 : %s, 값 : %s", elem.getKey(), elem.getValue()) );
}

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


keySet()은 key값만 가져오기 때문에 value를 가져오기 위해서 get(key)를 사용해준다.

entry()은 key,value를 모두 가져온다.

 

많은 양의 데이터를 가져와야 한다면 key값을 이용해서 value를 찾는 과정이 오래 소모되므로 방법 2를 사용하는 것이 좋다고 한다.

+ Recent posts