day_by_day

6. Map 본문

QA Automation/dart

6. Map

kokorii_ 2023. 5. 15. 23:47

1. 선언 

  Map<String, String> dictionary = {
    'Harry Potter': '해리포터',
    'Ron Weasley' : '론 위즐리',
    'Hermione Granger' : '헤르미온느 그레인저',
  };

  print(dictionary);

  Map<String, bool> isHarryPotter= {
    'Harry Potter': true,
    'Ron Weasley' : true,
    'Ironman' : false
  };

  print(isHarryPotter);

2. 값 핸들링

- 추가 : addAll(), key-value 직접 입력

- 확인 : key를 이용한 접근

- 변경 : key를 이용하여 직접 변경

- 삭제 : remove()

- map.keys, map.values -> map.keys.toList(), map.keys.toList()

  // 추가 
  isHarryPotter.addAll({
    'Spiderman' : false,
  });
  print(isHarryPotter);

  isHarryPotter['Hulk'] = false;
  print(isHarryPotter);
 

  //key를 이용한 value 데이터 확인 
  print(isHarryPotter['Ironman']);


  //값 변경 
  isHarryPotter['Spiderman'] = true; 
  print(isHarryPotter);

  
  //값 삭제
  isHarryPotter.remove('Harry Potter');
  print(isHarryPotter);

  //keys, values
  print(isHarryPotter.keys);
 print(isHarryPotter.values);

 /*************************************/
 
  Map map = {
    'apple':'사과',
    'banana': '바나나',
    'kiwi' : '키위',
  };
  
  print(map.values);
  print(map.keys);

  print(map.keys.toList());
  print(map.values.toList());

3. Mapping - entry

- map의 entires 를 이용하여 key, value map을 생성 또는 핸들링 할 수 있음

  final newMap = map.entries.map((entry){
    final key = entry.key;
    final value = entry.value;

    return '$key 는 한글로 $value 입니다.';
  });

  print(newMap);

4. forEach, Reduce, Fold

  map.entries.forEach((entry){

    final key = entry.key;
    final value = entry.value;

    print('$key 는 한글로 $value 입니다.');

  });

  final total = map.entries.fold(0,(total, entry){
    return total + entry.key.toString().length;
  });

  print(total);

5. List to Map 변경하여 index 찾기

- list를 map으로 만들어 key,value mapping 할 수 있음 

  List<int> nums = [10,20,30,40,50];

  final map2 =  nums.map((item){
    return 'value is $item';});
  print(map2);

  final map3 = nums.asMap().entries.map((entry){
    final index = entry.key;
    final value = entry.value;

    return 'index = ${index}, value = ${value}';
  });
  print(map3);

}

 

'QA Automation > dart' 카테고리의 다른 글

8. Typedef  (3) 2023.05.16
7. 함수(function)  (1) 2023.05.16
5. List  (3) 2023.05.15
4. 열거형 Enum  (0) 2023.05.15
3. Set  (1) 2023.05.15