본문 바로가기

JAVA

Map (Key, Value)

Map (Key, Value) : Key 이용해 Value 값을 얻음


기능 소개

put - HashMap 안에 데이터를 넣을 수 있다.

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

//entry 추가 메소드 : put
map.put("student1","손흥민");
map.put("student2","이강인");
map.put("student3","김민재");

키를 중복해서 put 하면 덮어씌워짐

 //entry 교체 메소드 : put
map.put("student3","박지성");

size - Map의 개수를 알 수 있다.

//map의 크기를 알고 싶을때 : size
map.size();
System.out.println("put 한 개수: " + map.size()); //3

 

remove - 삭제 메소드 key 값을 이용해 삭제

//entry 삭제 메소드 : remove
 map.remove("student2");

get - HashMap 안에 값을 불러온다. / Value 값이 나온다.

//entry value를 얻는 메소드 : get
map.get("student1");
System.out.println(map.get("student1")); //손흥민

map 전체 탐색 방법

1. Map.Entry<K,V>  

//향상된 for문 Set<Map.Entry<K,V>>
Set<Map.Entry<String, String>> entries = map.entrySet();

for(Map.Entry<String, String> entry: entries){
    System.out.println(entry);
    System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}

 

2. keyset - Map의 모든 key를 불러온다. / set 자료형으로 불러옴

//keyset
System.out.println(map.keySet()); //set의 형태로 나옴

//하나씩 추출
Set<String> keys = map.keySet();

for(String key : keys){
    System.out.println(key);
}

 

3. forEach 메소드로 전체 탐색

 //forEach
map.forEach(new BiConsumer<String, String>() {

    @Override
    public void accept(String key, String value) {
        System.out.println(key+ ": " + value);
    }
});


//람다로 변환하면 이런 형태가 나옴
map.forEach((key, value) -> System.out.println(key+ ": " + value));

getOrDefault - key안에 값이 없는 경우 null 대신 다른 값으로 사용 가능

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

//entry 추가
map.put("student1","손흥민");
map.put("student2","이강인");
map.put("student3","김민재");


System.out.println(map.getOrDefault("student1", "없음")); //손흥민
System.out.println(map.getOrDefault("student2", "없음")); //이강인
System.out.println(map.getOrDefault("student3", "없음")); //김민재
System.out.println(map.getOrDefault("student4", "없음")); //값이 없어 null 나와야 하지만 getOrDefault 로 인해 없음이 출력

containsKey - map 안에 key 가 있는지 확인

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

//entry 추가
map.put("student1","손흥민");
map.put("student2","이강인");
map.put("student3","김민재");


System.out.println(map.containsKey("student1")); //true
System.out.println(map.containsKey("student4")); //false

value도 가능하다.

System.out.println(map.containsValue("손흥민")); //true
System.out.println(map.containsValue("박지성")); //false

 

LinkedHashMap - 입력된 순서대로 데이터를 저장

 

TreeMap - 입력된 key의 오름차순 순서로 데이터를 저장


Map.of() - 수정 불가한 Map

// 수정 불가한 Map
Map<String, String> map = Map.of("name1","손흥민", "name2", "김민재");

map.put("name3", "이강인"); // 오류 발생

// 수정하고 싶은 경우
Map<String, String> map2 = new HashMap<>(map2);

map2.put("name3", "이강인"); // 추가 가능
반응형

'JAVA' 카테고리의 다른 글

switch/case  (0) 2022.10.13
if (참, 거짓)  (0) 2022.10.13
형 변환, final  (0) 2022.10.12
Set (집합)  (0) 2022.10.11
ArrayList (리스트) + Generics<> (제네릭스)  (0) 2022.10.07