Map - 컬렉션 프레임워크 - Map 소개2
2024. 6. 17. 06:10ㆍ김영한 Java/컬렉션 프레임워크
package collection.Map;
import java.util.HashMap;
import java.util.Map;
public class MapMain2 {
public static void main(String[] args) {
Map<String,Integer> studentMap = new HashMap<>();
//학생 성적 데이터 추가
studentMap.put("studentA",90);
System.out.println(studentMap);
studentMap.put("studentA",100);
System.out.println(studentMap);
boolean containsKey = studentMap.containsKey("studentA");
System.out.println("containsKey = " + containsKey);
//특정 학생의 값 삭제
studentMap.remove("studentA");
System.out.println(studentMap);
}
}
실행 결과
{studentA=90}
{studentA=100}
containsKey = true
{}
Map에 값을 저장할 때 같은 키에 다른 값을 저장하면 기존 값을 교체한다.
StudentA=90 에서 studentA=100으로 교체된걸 확인할 수 있다.
package collection.Map;
import java.util.HashMap;
import java.util.Map;
public class MapMain3 {
public static void main(String[] args) {
Map<String,Integer> studentMap = new HashMap<>();
//학생 성적 데이터 추가
studentMap.put("studentA",50);
System.out.println(studentMap);
//학생이 없는 경우에만 추가1
if(!studentMap.containsKey("studentA")){
studentMap.put("studentA",100);
}
System.out.println(studentMap);
//학생이 없는 경우에만 추가1
studentMap.putIfAbsent("studentA",100);
studentMap.putIfAbsent("studentB",100);
System.out.println(studentMap);
}
}
실행 결과
{studentA=50}
{studentA=50}
{studentB=100, studentA=50}
putIfAbsent()는 영어 그대로 없는 경우에만 입력하라는 뜻이다. 이 메서드를 사용하면 키가 없는 경우에만 데이터를 저장하고 싶을 때 코드 한줄로 편리하게 처리할 수 있다.
'김영한 Java > 컬렉션 프레임워크' 카테고리의 다른 글
| Stack - 스택 자료 구조 (0) | 2024.06.17 |
|---|---|
| Map - 컬렉션 프레임워크 - Map 구현체 (0) | 2024.06.17 |
| Map - 컬렉션 프레임워크 - Map 소개 1 (0) | 2024.06.17 |
| Set - 자바가 제공하는 Set4 - 최적화 (0) | 2024.06.14 |
| Set - 자바가 제공하는 Set2 - TreeSet (0) | 2024.06.14 |