JAVA Collection Map

sung eon·2022년 5월 19일
0

JAVA

목록 보기
16/21

map

key에 해당하는 타입, value에 해당하는 타입 두개가 들어가야 하므로 <> 안에 두개를 적어준다.
add 대신 put

map 살펴보기

Map<Integer, String> map = ner HashMap<>();
map.put(1, "apple");
map.put(2, "berry");
map.put(3, "cherry");

System.out.println(map);

{1=apple, 2=berry, 3=cherry}

n번째 값 가져오기
예제에선 첫번쨰 값.

Map<Integer, String> map = ner HashMap<>();
map.put(1, "apple");
map.put(2, "berry");
map.put(3, "cherry");

System.out.println(map);

System.out.println("1st in map: " + map.get(0));

1st in map: null

_ 이때! map.get() 괄호 안에는 index 값이 아니라 key값이 들어가야한다! 따라서,

Map<Integer, String> map = ner HashMap<>();
map.put(1, "apple");
map.put(2, "berry");
map.put(3, "cherry");

System.out.println(map);

System.out.println("1st in map: " + map.get(1));

1st in map: apple

이라고 나온다.


값 지우기!

Map<Integer, String> map = ner HashMap<>();
map.put(1, "apple");
map.put(2, "berry");
map.put(3, "cherry");

System.out.println(map);

System.out.println("1st in map: " + map.get(1));

map.remove( ket: 2);
System.out.println(map);

{1=apple, 3=cherry}


key / value 로 해당 값 있는지 boolean!

Map<Integer, String> map = ner HashMap<>();
map.put(1, "apple");
map.put(2, "berry");
map.put(3, "cherry");

System.out.println(map);

System.out.println("1st in map: " + map.get(1));

map.remove( ket: 2);
System.out.println(map);

System.out.println(map.containsKey(2));
System.out.println(map.containsValue("cherry"));

false
true

profile
코베베

0개의 댓글