[자료구조] HashMap

2023. 8. 1. 14:30·CS 지식/[자료구조]
목차
  1. HashMap
  2. HashMap 선언
  3. HashMap 값 추가하기
  4. HashMap 값 삭제하기
  5. HashMap 크기 구하기
  6. HashMap 값 출력하기

HashMap

  • Map인터페이스에 속해있는 컬렉션
  • 키 : 값 - 1 : 1

HashMap 선언

import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap hm = new HashMap(); // 타입 설정x Object 입력
HashMap<Integer, Integer> i = new HashMap<>(); // Integer, Integer 타입 설정
HashMap<Integer, Integer> i2 = new HashMap<>(i); // i의 값을 i2에 카피
HashMap<Integer, Integer> i3 = new HashMap<>(10); // 초기용량 지정
HashMap<Integer, Integer> i4 = new HashMap<>() {{ // 변수 선언 + 초기값 지정
put(1, 100);
put(2, 200);
}};
HashMap<String, String> str = new HashMap<String, String>(); // String, String 타입 설정
HashMap<Character, Character> ch = new HashMap<Character, Character>(); // Char, Char 타입 설정
}
}
  • Key, Value 2개의 값을 가지고 있으므로 두 개의 타입을 선언해야 함
  • HashMap<타입, 타입> 변수명 = new HashMap<타입, 타입>();

HashMap 값 추가하기

  • put(Key, Value)를 사용
HashMap<String, String> hm = new HashMap<String, String>(); // HashMap 선언
// 값 추가
hm.put("1", "Hello1");
hm.put("2", "World2");
hm.put("3", "Hello3");
hm.put("4", "World4");
hm.put("2", "WorldWorld2");
System.out.print(hm); // 결과 출력

 

HashMap 값 삭제하기

  • remove(Key) 메서드를 사용
  • clear()메서드를 사용하면 HashMap의 모든 키 값을 삭제
HashMap<String, String> hm = new HashMap<String, String>(); // HashMap 선언
// 값 추가
hm.put("1", "Hello1");
hm.put("2", "World2");
hm.put("3", "Hello3");
hm.put("4", "World4");
System.out.println(hm); // 결과 출력
hm.remove("3");
System.out.println(hm); // 결과 출력
hm.clear();
System.out.println(hm); // 결과 출력



HashMap 크기 구하기

  • size() 메서드를 사용
HashMap<String, String> hm = new HashMap<String, String>(); // HashMap 선언
// 값 추가
hm.put("1", "Hello1");
hm.put("2", "World2");
hm.put("3", "Hello3");
hm.put("4", "World4");
System.out.println(hm); // 결과 출력
System.out.println("Size : " + hm.size());



HashMap 값 출력하기

[첫 번째 방법]

  • 향상된for문을 사용
  • or(Map.Entry<타입, 타입> 변수명 : entrySet()) 을 사용하여 HashMap을 반복문을 실행
  • e.getKey(), e.getValue() 메서드를 차례대로 사용하여 HashMap의 Key값과 Value값을 가져올 수 있음
HashMap<String, String> hm = new HashMap<String, String>(); // HashMap 선언
// 값 추가
hm.put("1", "Hello1");
hm.put("2", "World2");
hm.put("3", "Hello3");
hm.put("4", "World4");
for(Map.Entry<String, String> e : hm.entrySet())
System.out.println("Key : " + e.getKey() + ", Value : " + e.getValue());

[두 번째 방법]

  • Iterator방식을 사용
HashMap<String, String> hm = new HashMap<String, String>(); // HashMap 선언
// 값 추가
hm.put("1", "Hello1");
hm.put("2", "World2");
hm.put("3", "Hello3");
hm.put("4", "World4");
Iterator<Entry<String, String>> iter = hm.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
}
System.out.println("-----------------------------");
Iterator<String> iter2 = hm.keySet().iterator();
while(iter2.hasNext()) {
String key = iter2.next();
System.out.println("Key : " + key + ", Value : " + hm.get(key));
}

 

 

참고
https://crazykim2.tistory.com/587

저작자표시 비영리 변경금지 (새창열림)

'CS 지식 > [자료구조]' 카테고리의 다른 글

[자료구조] 빅오 표기법(big-O notation)  (1) 2023.10.20
[자료구조] 자료구조  (1) 2023.10.20
[자료구조] 해시(Hash)  (0) 2023.07.19
[자료구조] 이진 탐색 트리(Binary Search Tree)  (0) 2023.07.19
[자료구조] 트리(Tree)  (0) 2023.07.19
  1. HashMap
  2. HashMap 선언
  3. HashMap 값 추가하기
  4. HashMap 값 삭제하기
  5. HashMap 크기 구하기
  6. HashMap 값 출력하기
'CS 지식/[자료구조]' 카테고리의 다른 글
  • [자료구조] 빅오 표기법(big-O notation)
  • [자료구조] 자료구조
  • [자료구조] 해시(Hash)
  • [자료구조] 이진 탐색 트리(Binary Search Tree)
woojin._.
woojin._.
여러가지 개발을 해보며 발생하는 이야기들에 대한 블로그입니다:)
  • woojin._.
    Jin's Dev Story
    woojin._.
  • 전체
    오늘
    어제
    • 분류 전체보기 (794)
      • Tools (25)
        • eGovFrame (3)
        • GeoServer (3)
        • QGIS (2)
        • LabelImg (2)
        • Git (6)
        • GitHub (1)
        • Eclipse (7)
        • Visual Studio (1)
      • Web & Android (121)
        • SpringBoot (37)
        • Three.js (2)
        • Spring Data JPA (9)
        • 스프링 부트 쇼핑몰 프로젝트 with JPA (25)
        • Thymeleaf (4)
        • Spring Security (15)
        • Flutter (29)
      • Programming Language (61)
        • JAVA (27)
        • JavaScript (14)
        • Dart (2)
        • Python (15)
        • PHP (3)
      • Database (43)
        • PostgreSQL (32)
        • MYSQL (7)
        • Oracle (3)
        • MSSQL (1)
      • SERVER (17)
        • TCP_IP (3)
        • 리눅스 (7)
        • AWS (7)
      • Coding Test (410)
        • 백준[JAVA] (76)
        • 프로그래머스[JAVA] (257)
        • 알고리즘 고득점 Kit[JAVA] (3)
        • SQL 고득점 Kit[ORACLE] (74)
      • CS 지식 (49)
        • [자료구조] (14)
        • [네트워크] (12)
        • [데이터베이스] (10)
        • [알고리즘] (9)
        • [운영체제] (4)
      • 기타 (6)
      • 자격증 & 공부 (62)
        • 정보처리기사 (2)
        • SQLD (6)
        • 네트워크관리사 2급 (5)
        • 리눅스마스터 1급 (44)
        • 리눅스마스터 2급 (1)
        • ISTQB (3)
        • 시스템보안 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    baekjoon
    postgresql
    플러터
    Java
    springboot
    programmers
    CS
    python
    자바
    Oracle
    리눅스
    DB
    스프링
    Linux
    백준
    spring
    스프링부트
    데이터
    Flutter
    스프링 부트 쇼핑몰 프로젝트 with JPA
    데이터베이스
    JPA
    리눅스마스터
    CS지식
    backjoon
    pcce 기출문제
    프로그래머스
    리눅스마스터 1급
    시큐리티
    Spring Security
  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
woojin._.
[자료구조] HashMap

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.