교육

HashMap 메소드

행복하게사는게꿈 2020. 10. 5. 15:28

HashMap

 

HashMap은 Map 인터페이스를 구현한 대표적인 Map 컬렉션.

 

map 인터페이스를 상속하고 있기에 Map의 성질을 그대로 가지고 있다

 

Map은 키, 값으로 구성된 Entry객체를 저장하는 구조

 

 * 여기서 키와 값은 모두 객체

 

값은 중복 저장 될 수 있지만 키는 중복 저장될 수 없다.

 

기존에 저장된 키와 동일한 키로 값을 저장하면 기존의 값은 없어지고 새로운 값으로 대치

 

HashMap은 이름 그대로 해싱(hashing)을 사용하기 때문에 많은 양의 데이터를 검색하는데 있어 뛰어난 성능

 

사용자는 hashMap에 저장되는 위치나 순서를 알 수 없다.

 

 

메소드

 

HashMap 생성

Map<String, Integer> map = new HashMap<String, Integer>(); 

 * hashMap을 사용하려면 객체를 생성해야 한다.

 

put(K key, V value)

삽입 메소드

map.put("신논현", 1);
map.put("강남", 2);
map.put("혜화", 3);
map.put("안양", 4);
map.put("수원", 5);

 

 

putAll(Map m)

 

하나의 Map을 또 다른 Map에 추가

Map<String, Integer> map = new HashMap<String, Integer>();

map.put("신논현", 1);
map.put("강남", 2);
map.put("혜화", 3);
map.put("안양", 4);
map.put("수원", 5);

Map<String, Integer> map2 = new HashMap<String, Integer>();

map.put("천안", 6);
map.put("양평", 7);
map.put("장성", 8);
map.put("파주", 9);
map.put("부산", 10);

map.putAll(map2);

 

remove(Object Key)

 

하나의 key를 입력하여 데이터를 삭제

map.remove("신논현");

 

size()

 

HashMap에 저장된 엘리먼트의 개수를 반환

System.out.println(map.size());

 

values()

 

HashMap에 저장된 엘리먼트들을 전부 컬렉션 형태로 출력

HashMap<String , Integer> map = new HashMap<String , Integer>();

    map.put("신논현", 1);
    map.put("강남", 2);
    map.put("혜화", 3);
    map.put("안양", 4);
    map.put("수원", 5);

    System.out.println(map.values());
    
    출력 결과 : [5, 4, 3, 2, 1]

isEmpty()

 

컬렉션에서 엘리먼트의 유무 체크

if(map.isEmpty()){
	System.out.println("엘리먼트가 없습니다.");
}else{
	System.out.println("엘리먼트가 있습니다..");
}

 

get(Object Key)

 

map.get("강남");

 

clear()

 

Map에 있는 엘리먼트를 깔끔하게 비워냄

map.clear();

 

clone()

 

해당 map의 엘리먼트들을 복제

 

HashMap<String , Integer> map = new HashMap<String , Integer>();

    map.put("신논현", 1);
    map.put("강남", 2);
    map.put("혜화", 3);
    map.put("안양", 4);
    map.put("수원", 5);

HashMap<String, Integer> map2 = (HashMap<String, Integer>) map.clone();

 

containsKey(Object Key)

 

map의 엘리먼트 중 key를 포함하고 있는지 여부 확인

HashMap<String , Integer> map = new HashMap<String , Integer>();

    map.put("신논현", 1);
    map.put("강남", 2);
    map.put("혜화", 3);
    map.put("안양", 4);
    map.put("수원", 5);

    System.out.println(map.containsKey("혜화"));

 * 만약 엘리먼트 내에 Key가 포함되어 있다면 boolean값으로 true, 아니라면 false가 리턴

 

containsValue(Object Value)

 

map의 엘리먼트 중 value를 포함하고 있는지 여부 확인

HashMap<String , Integer> map = new HashMap<String , Integer>();

    map.put("신논현", 1);
    map.put("강남", 2);
    map.put("혜화", 3);
    map.put("안양", 4);
    map.put("수원", 5);

    System.out.println(map.containsValue(5));

 

set entrySet()

 

hashMap에 저장된 key, value 값을 엔트리(키와 값을 결합)의 형태로 Set에 저장하여 반환

HashMap<String , Integer> map = new HashMap<String , Integer>();

    map.put("신논현", 1);
    map.put("강남", 2);
    map.put("혜화", 3);
    map.put("안양", 4);
    map.put("수원", 5);

    Set set = map.entrySet();

    System.out.println(set);
    
    출력 결과 : [수원=5, 안양=4, 혜화=3, 강남=2, 신논현=1]

 

hashMap 값 출력 방법

HashMap<Integer,String> map = new HashMap<Integer,String>(){{//초기값 지정
    put(1,"사과");
    put(2,"바나나");
    put(3,"포도");
}};
		
System.out.println(map); //전체 출력 : {1=사과, 2=바나나, 3=포도}
System.out.println(map.get(1));//key값 1의 value얻기 : 사과
		
//entrySet() 활용
for (Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("[Key]:" + entry.getKey() + " [Value]:" + entry.getValue());
}
//[Key]:1 [Value]:사과
//[Key]:2 [Value]:바나나
//[Key]:3 [Value]:포도

//KeySet() 활용
for(Integer i : map.keySet()){ //저장된 key값 확인
    System.out.println("[Key]:" + i + " [Value]:" + map.get(i));
}
//[Key]:1 [Value]:사과
//[Key]:2 [Value]:바나나
//[Key]:3 [Value]:포도

 

Iterator를 사용해서 출력

HashMap<Integer,String> map = new HashMap<Integer,String>(){{//초기값 지정
    put(1,"사과");
    put(2,"바나나");
    put(3,"포도");
}};
		
//entrySet().iterator()
Iterator<Entry<Integer, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
    Map.Entry<Integer, String> entry = entries.next();
    System.out.println("[Key]:" + entry.getKey() + " [Value]:" +  entry.getValue());
}
//[Key]:1 [Value]:사과
//[Key]:2 [Value]:바나나
//[Key]:3 [Value]:포도
		
//keySet().iterator()
Iterator<Integer> keys = map.keySet().iterator();
while(keys.hasNext()){
    int key = keys.next();
    System.out.println("[Key]:" + key + " [Value]:" +  map.get(key));
}
//[Key]:1 [Value]:사과
//[Key]:2 [Value]:바나나
//[Key]:3 [Value]:포도