[왕초보 무료 프로그래밍 언어 강의] [Dart] #8 — Map 타입

Ji Ho Choi
코드팩토리
Published in
4 min readOct 15, 2020

--

Map 타입

void main(){
Map dictionary = {
'Harry Potter': '해리포터',
'Ron Weasley' : '론 위즐리',
'Hermione Granger' : '헤르미온느 그레인저',
};
Map<String, bool> isHarryPotterCharacter = {
'Harry Potter': true,
'Ron Weasley' : true,
'Ironman' : false,
};
print(dictionary);
print(isHarryPotterCharacter);
}
  • 맵 타입을 선언할 때는 Map 이라는 키워드를 사용하거나 Map 이라는 키워드에 괄호로 어떤 key 타입과 value 타입이 들어갈지 미리 결정을 하고 선언할 수 있다.

Map 타입 Key, Value 추가 및 수정

void main(){
Map<String, bool> isHarryPotterCharacter = {
'Harry Potter': true,
'Ron Weasley' : true,
'Ironman' : false,
};
print(isHarryPotterCharacter);

isHarryPotterCharacter.addAll({
'Spiderman': false,
});
print(isHarryPotterCharacter); isHarryPotterCharacter['Hulk'] = false; print(isHarryPotterCharacter); isHarryPotterCharacter['Spiderman'] = true; print(isHarryPotterCharacter);
}
  • 맵 타입에 key, value 를 추가할때는 addAll 이라는 메소드를 사용하거나 괄호를 사용한다.
  • 이미 key 가 존재하는 경우 해당 key 의 value 를 덮어씌운다.

Map 타입 Key, Value 삭제

void main(){
Map<String, bool> isHarryPotterCharacter = {
'Harry Potter': true,
'Ron Weasley' : true,
'Ironman' : false,
};
print(isHarryPotterCharacter); isHarryPotterCharacter.remove('Ironman'); print(isHarryPotterCharacter);
}
  • Key, Value 를 삭제하기 위해서는 Map 의 remove 메소드를 사용한다. Remove 메소드에는 삭제하고 싶은 pair 의 Key 값을 입력한다.

Map 타입 Key, Value 리스팅

void main(){
Map<String, bool> isHarryPotterCharacter = {
'Harry Potter': true,
'Ron Weasley' : true,
'Ironman' : false,
};
print(isHarryPotterCharacter); print(isHarryPotterCharacter.keys);
print(isHarryPotterCharacter.values);
print(isHarryPotterCharacter['Harry Potter']);
}
  • 모든 Key 값을 프린트하고 싶을 때는 .keys 를 사용한다.
  • 모든 value 값을 프린트하고 싶을 때는 .values 를 사용한다.
  • value 하나를 가져오고 싶을 때는 괄호를 사용하고 괄호에 key 값을 넣는다.

--

--