기억을 지배하는 기록

Dart의 컬렉션(Collection) 본문

Flutter for Beginners

Dart의 컬렉션(Collection)

Andrew's Akashic Records 2025. 2. 19. 13:00
728x90

Flutter and Dart

Dart의 컬렉션(Collection) 타입

Dart에서 컬렉션(Collection) 타입은 여러 개의 값을 저장하고 조작할 수 있는 자료 구조입니다.
대표적인 컬렉션 타입은 List(리스트), Set(집합), Map(맵)이 있습니다.

1. List (리스트, 배열)

Dart의 List는 배열과 같은 개념으로, 순서가 있는 데이터 모음을 저장합니다.

(1) 리스트 선언 및 초기화

void main() {
  // 정수 리스트
  List<int> numbers = [1, 2, 3, 4, 5];

  // 문자열 리스트
  List<String> fruits = ["Apple", "Banana", "Cherry"];

  // 타입을 지정하지 않은 리스트 (dynamic)
  List mixedList = [1, "Hello", true, 3.14];

  print(numbers);    // [1, 2, 3, 4, 5]
  print(fruits[0]);  // Apple
  print(mixedList);  // [1, Hello, true, 3.14]
}

리스트는 0부터 시작하는 인덱스(index) 를 사용하여 요소를 접근합니다.

(2) 리스트 조작 (추가, 삭제, 수정)

void main() {
  List<String> fruits = ["Apple", "Banana"];

  // 요소 추가
  fruits.add("Cherry");  
  print(fruits);  // [Apple, Banana, Cherry]

  // 여러 개 추가
  fruits.addAll(["Grapes", "Mango"]);
  print(fruits);  // [Apple, Banana, Cherry, Grapes, Mango]

  // 특정 위치에 추가
  fruits.insert(1, "Pineapple");
  print(fruits);  // [Apple, Pineapple, Banana, Cherry, Grapes, Mango]

  // 요소 삭제
  fruits.remove("Banana");
  print(fruits);  // [Apple, Pineapple, Cherry, Grapes, Mango]

  // 인덱스로 삭제
  fruits.removeAt(0);
  print(fruits);  // [Pineapple, Cherry, Grapes, Mango]

  // 마지막 요소 삭제
  fruits.removeLast();
  print(fruits);  // [Pineapple, Cherry, Grapes]

  // 모든 요소 삭제
  fruits.clear();
  print(fruits);  // []
}

(3) 리스트 반복문

void main() {
  List<int> numbers = [10, 20, 30];

  // for 문
  for (int i = 0; i < numbers.length; i++) {
    print(numbers[i]);
  }

  // for-in 문
  for (var num in numbers) {
    print(num);
  }

  // forEach() 메서드
  numbers.forEach((num) {
    print(num);
  });
}

(4) 리스트 필터링 (where 사용)

void main() {
  List<int> numbers = [10, 25, 30, 45, 50];

  var evenNumbers = numbers.where((num) => num % 2 == 0);
  print(evenNumbers.toList());  // [10, 30, 50]
}

(5) 불변 리스트 (const 사용)

리스트가 변경되지 않도록 불변(Immutable) 리스트를 만들 수 있습니다.

void main() {
  List<int> fixedList = const [1, 2, 3];

  // fixedList.add(4); // 오류 발생 (수정 불가)
  print(fixedList);  // [1, 2, 3]
}

2. Set (집합)

Set은 중복된 요소를 허용하지 않는 컬렉션입니다.

(1) Set 선언 및 초기화

void main() {
  Set<int> numbers = {1, 2, 3, 3, 4, 4, 5};

  print(numbers);  // {1, 2, 3, 4, 5} (중복 제거됨)
}

(2) Set 조작

void main() {
  Set<String> fruits = {"Apple", "Banana"};

  // 요소 추가
  fruits.add("Cherry");
  fruits.add("Apple");  // 이미 존재하는 값 (추가되지 않음)
  
  print(fruits);  // {Apple, Banana, Cherry}

  // 요소 삭제
  fruits.remove("Banana");
  print(fruits);  // {Apple, Cherry}

  // 포함 여부 확인
  print(fruits.contains("Apple"));  // true
}

Set은 빠른 검색 및 중복 제거가 필요할 때 유용합니다.

(3) Set 연산

void main() {
  Set<int> a = {1, 2, 3, 4};
  Set<int> b = {3, 4, 5, 6};

  print(a.union(b));       // 합집합: {1, 2, 3, 4, 5, 6}
  print(a.intersection(b)); // 교집합: {3, 4}
  print(a.difference(b));   // 차집합: {1, 2}
}

집합 연산(union, intersection, difference)을 사용할 수 있음.

3. Map (딕셔너리, Key-Value 구조)

Map은 키(Key)와 값(Value)으로 이루어진 컬렉션입니다.

(1) Map 선언 및 초기화

void main() {
  Map<String, int> scores = {
    "Math": 90,
    "English": 85,
    "Science": 95
  };

  print(scores["Math"]);  // 90
}

scores["Math"] 처럼 키를 이용해 값을 가져올 수 있음.

(2) Map 조작

void main() {
  Map<String, String> student = {
    "name": "John",
    "age": "20"
  };

  // 요소 추가
  student["grade"] = "A";
  print(student);  // {name: John, age: 20, grade: A}

  // 요소 삭제
  student.remove("age");
  print(student);  // {name: John, grade: A}

  // 모든 키 가져오기
  print(student.keys);  // (name, grade)

  // 모든 값 가져오기
  print(student.values);  // (John, A)
}

keys와 values를 사용하여 키와 값을 가져올 수 있음.

(3) Map 반복문

void main() {
  Map<String, int> scores = {
    "Math": 90,
    "English": 85
  };

  // forEach() 사용
  scores.forEach((key, value) {
    print("$key: $value");
  });

  // for-in 사용
  for (var key in scores.keys) {
    print("$key: ${scores[key]}");
  }
}

forEach()와 for-in을 사용하여 Map을 반복할 수 있음.

4. 컬렉션 변환

컬렉션 간 변환이 가능하며, map(), toList(), toSet() 등을 활용할 수 있습니다.

void main() {
  List<int> numbers = [1, 2, 3, 4];

  // 리스트 → Set
  Set<int> numberSet = numbers.toSet();
  print(numberSet);  // {1, 2, 3, 4}

  // Set → 리스트
  List<int> numberList = numberSet.toList();
  print(numberList);  // [1, 2, 3, 4]

  // 리스트 변환 (2배 증가)
  var doubled = numbers.map((num) => num * 2).toList();
  print(doubled);  // [2, 4, 6, 8]
}

 

728x90

'Flutter for Beginners' 카테고리의 다른 글

Dart의 연산자  (0) 2025.02.20
Dart의 enum  (0) 2025.02.19
Dart의 dynamic 변수 타입  (0) 2025.02.18
Dart 기초 문법  (0) 2025.02.18
Dart 실습 환경  (0) 2025.02.18
Comments