key : value의 값을 가지는 하나의 자료구조
무언가를 찾기 위한 검색어 (이름) = key
그 검색어로 나온 결과 (전화번호) = value
(전화번호, 이름) 쌍의 데이터 100만개가 있다고 가정하다. (전화번호 중복 X)
만약 배열에 100만개의 데이터를 저장하고, 짧은 시간에 수 많은 검색이 필요하다면 100만개의 데이터를 모두 확인하는데 상당한 시간이 소요될 것이다. (데이터 조회 한 건당 O(n))
반면 Key를 전화번호, Values를 이름으로 하는 HashMap에 데이터를 저장한다면 O(1)의 시간복잡도로 원하는 데이터를 얻을 수 있다.
HashMap 메서드 시간복잡도
get : O(1)
containsKey : O(1)
// 선언
HashMap<타입 ,타입> hm = new HashMap<>();
// 카피 - 타입이 모두 같아야 함.
HashMap<타입, 타입> hm2 = new HashMap<>(hm);
// 크기 지정
HashMap<타입, 타입> hm3 = new HashMap<>(크기);
public class Main {
public static void main(String[] args) {
Map<String, Integer> hm = new HashMap<>();
// 데이터 추가
hm.put("data1", 1);
hm.put("data2", 2);
hm.put("data3", 3);
hm.put("data4", 4);
hm.put("data5", 3);
hm.put("data6", 6);
// 데이터 삭제 - key
hm.remove("data1");
// 데이터 삭제 - values
// (**동일한 값이 존재하는 경우 가장 늦게 들어온 오직 한 개의 요소만 삭제**)
// hm.values().remove(3);
// 결과 : {data6=6, data4=4, data3=3, data2=2}
// 데이터 삭제 - values - 한 번에 여러 요소 삭제
// value가 2,3인 모든 데이터를 삭제한다.
// hm.values().removeAll(Arrays.asList(2,3));
// HashMap 크기
hm.size();
// 모든 내용 삭제
// hm.clear();
// 데이터 변경
hm.replace("data2", 10);
hm.replace("data6", 6, 12); // 키의 값이 일치해야 값 변경 가능
// 데이터 추출
hm.get("data2"); // 키로 값 추출
// 키 존재 유무 확인 true|false
hm.containsKey("data6"); // 키 기준
hm.containsValue(12); // 값 기준
}
}
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) {
Map<String, Integer> hm = new HashMap<>();
Map<String, String> map = new HashMap<>();
map.put("Ghana", "Accra");
map.put("United States", "Washington");
map.put("Greece", "Athens");
map.put("England", "London");
map.put("Australia", "Canberra");
List<String> valueList = new ArrayList<>(map.values());
valueList.sort((o1, o2) -> {
return o1.compareTo(o2);
}); // 알파벳 순으로 정렬
for (String value : valueList) {
System.out.println("Value: " + value);
}
}
}
/*
Value: Accra
Value: Athens
Value: Canberra
Value: London
Value: Washington
*/
public class test {
public static void main(String[] args) {
Map<String, Integer> hm = new HashMap<>();
Map<String, String> map = new HashMap<>();
map.put("Ghana", "Accra");
map.put("United States", "Washington");
map.put("Greece", "Athens");
map.put("England", "London");
map.put("Australia", "Canberra");
List<String> keyList = new ArrayList<>(map.keySet());
keyList.sort((o1, o2) -> {
return o1.compareTo(o2);
}); // 알파벳 순으로 정렬
for (String key : keyList) {
System.out.println("Key: " + key);
}
}
}
/*
Key: Australia
Key: England
Key: Ghana
Key: Greece
Key: United States
*/