[Dart] iterable 의미와 Collection 의 종류

오묘(吳猫)·2022년 5월 17일
1

Dart

목록 보기
3/5
post-thumbnail

1. iterable 의미

A collection of values, or "elements", that can be accessed sequentially.
collection 이며, 순서가 있어야 한다.(sequentially)
출처 : flutter.dev

Dart 에는 iterable 이라는 개념이 있습니다.
우리말로 번역하면 '반복이 가능한 집단' 이란 의미로, list, array 등을 의미합니다.
참고로 기본 Map 은 순서가 없으므로 iterable 이 아니지만, linked Map 은 순서가 있으므로 iterable 입니다.

자료 구조에서는 iterablefor문 처럼 한바퀴 돌릴 수 있는 자료 구조를 의미합니다.
listlinked Map 은 다음 data 의 위치를 알 수 있으므로 iterable,
Map 의 경우 Key-value 구조이기 때문에 iterate 포함할 수 없습니다.


2. Collection

- List

데이터를 순차적으로 담을 수 있는 인덱싱이 가능한 자료구조로 중복을 허용합니다.
배열을 대체 할 수 있습니다.

👉 예제

void main() {
  // list
  // 리스트
  List<String> lol = ['징크스', '가렌', '티모', '유미'];
  List<int> number = [1, 2, 3, 4, 5, 6];

  print(lol);
  print(number);

  // index
  // 순서
  // 0 부터 시작
  print(lol[0]); // 징크스
  print(lol[1]); // 가렌
  print(lol[0]); // 징크스
  print(lol[1]); // 가렌
}

- Map

키(Key)와 값(Value)으로 구성된 클래스로서
키는 중복을 허용하지 않고 값은 중복을 허용합니다.

map 함수는 iterable(배열그룹)을 대상으로 forEach를 돌립니다.
안에 넣어진 함수는 인자로 iterable 하나의 요소를 받기 때문에
반드시 '하나'의 widget(flutter가 아닌 곳에선 어떤 객체)을 return 해야합니다.

그래서 종종 .tolist 를 뒤에 붙여서 리스트로 list 로 값을 받습니다.
map 메소드가 실행되면 iterable의 요소수만큼 함수가 호출됩니다.

👉 예제

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

  print(dictionary); // {Harry Potter: 해리포터, Ron Weasley: 론 위즐리, Hermione Granger: 헤르미온느 그레인저}

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

  isHarryPotter.addAll({
    'Spiderman' : false,
  });
  print(isHarryPotter); // {Harry Potter: true, Ron Weasley: true, Ironman: false, Spiderman: false}
  print(isHarryPotter['Ironman']); // false

  isHarryPotter['Hulk'] = false;
  print(isHarryPotter); // {Harry Potter: true, Ron Weasley: true, Ironman: false, Spiderman: false, Hulk: false}

  isHarryPotter['Spiderma'] = true;
  print(isHarryPotter); // {Harry Potter: true, Ron Weasley: true, Ironman: false, Spiderman: false, Hulk: false, Spiderma: true}

  isHarryPotter.remove('Harry Potter');

  print(isHarryPotter); // {Ron Weasley: true, Ironman: false, Spiderman: false, Hulk: false, Spiderma: true}
  
  // 키 값만 가져오기
  print(isHarryPotter.keys); // (Ron Weasley, Ironman, Spiderman, Hulk, Spiderma)

  // 벨류 값만 가져오기
  print(isHarryPotter.values); // (true, false, false, false, true)

}

- Set

List 와 마찬가지로 데이터를 순차적으로 담을 수 있는 인덱싱이 가능한 자료구조이나 중복을 허용하지 않기 때문에 자동으로 중복을 처리 해준다는 장점이 있습니다.

👉 예제

void main() {
  // Set
  final Set<String> names = {
    'Dart',
    'Flutter',
    'Flutter',
  };
  print(names); // {Dart, Flutter}

  names.add('Laravel'); // 추가
  print(names); // {Dart, Flutter, Laravel}

  names.remove('Laravel'); // 삭제
  print(names); // {Dart, Flutter}
  
  print(names.contains('Flutter')); // true
}

## add, addAll, length, remove, clear

👉 ** 예제**
``` dart
void main() {
  // 문자열을 사용하여 list 생성
  var pokemon =['피카츄', '라이츄', '파이리', '꼬북이'];

  // list 에 값 추가
  pokemon.add('버터풀');
  print(pokemon); // 피카츄, 라이츄, 파이리, 꼬북이, 버터풀

  // list 에 다수의 요소 추가
  pokemon.addAll(['야도란', '피존투', '또가스']);
  print(pokemon);

  // list 의 길이
  print(pokemon.length); // 8

  // Index 의 위치 확인
  var pikachuIndex = pokemon.indexOf('피카츄');
  print(pikachuIndex); // 0
  
  // list 단일 요소 삭제
  pokemon.removeAt(pikachuIndex);
  pokemon.remove('라이츄');
  
  print(pokemon); // [파이리, 꼬북이, 버터풀, 야도란, 피존투, 또가스]

  // list 의 모든 항목 삭제
  pokemon.clear();
  print(pokemon); // []
}
profile
괴발개발 기록일지

0개의 댓글