난 주로 코딩테스트 할 때 hashMap을 사용하여 문제를 푼 경우가 많이 있다. 그런데 할 때마다 hashMap 사용법을 찾아보고 문제를 해결하는 경우가 많다. 따라서 여기에 hashMap 사용법을 기록하려고 한다.
간단하게 말하면
HashMap은 내부에 '키'와 '값'을 저장하는 자료 구조
이다. 특징으로는 키를 통해 값을 찾으므로 검색이 빠르다는 장점이 있다. 그리고 hashMap은 중복은 허용하지 않는다.
사용법은 아래에 공식문서를 참고했다.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html
HashMap<type,type> map = new HashMap<>();
Associates the specified value with the specified key in this map.
map.put(key, value);
Removes the mapping for the specified key from this map if present.
map.remove(key);
Removes all of the mappings from this map.
map.clear();
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
map.get(key); // print value
Returns a Set view of the keys contained in this map.
for(Integer i : map.keySet()){
System.out.println(i); // print key
}
Returns key and value
for (Entry<Integer, String> entrySet : map.entrySet()) {
System.out.println(entrySet.getKey() + " : " + entrySet.getValue());
}
key 정렬
keySet() 함수 같은 경우 자동으로 오름차순 정렬을 해준다.
HashMap<type,type> map = new HashMap<>();
... // 값 삽입 생략
List<type> list = new ArrayList<>(map.keySet());
Collections.reverse(list); 내림차순
value 정렬
HashMap<type,type> map = new HashMap<>();
... // 값 삽입 생략
List<type> list = new ArrayList<>(map.keySet());
list.sort((o1, o2) -> map.get(o1).compareTo(map.get(o2))); // 오름차순
list.sort((o1, o2) -> map.get(o2).compareTo(map.get(o1))); // 내림차순
나머지 함수는 앞으로 문제를 풀면서 추가할 예정이다.