Dart - 컬렉션(Collections)

목진성·2024년 10월 28일

Dart Language

목록 보기
3/12

컬렉션은 여러 개의 값을 하나의 그룹으로 묶어서 효율적으로 관리할 수 있는 친구입니다.
링크텍스트

종류

1. List

list는 많은 분들이 보셨을만한 아이인데요. 그냥 값을 넣어주는 순서대로 저장됩니다.

2. Set

list와 같은 아이인데 차이점이 있다면 list는 중복된 값이 저장되는 반면에 set은 중복 값을 제거해서 보여줍니다.

// List
List<int> numbers1 = [1, 2, 3, 4, 5];
print(numbers1); // 1, 2, 3, 4, 5

//Set
Set<int> numbers2 = {1, 2, 3, 4, 5, 1, 1, 1};
print(numbers2); // 1, 2, 3, 4, 5

List와 Set의 차이점

  • List는 Index를 통해 순서가 있는 반면 Set은 Index가 없기 때문에 순서가 없어요.
  • List는 중복된 값을 허용하는 반면에, Set은 중복을 허용하지 않습니다.

List, Set 더 알아보기
.length를 통해 요소의 개수를 구할 수 있어요.

final fruits = {'사과', '파인애플', '오렌지'};
print(fruits.length); // 3

.isEmpty( )를 통해 List 또는 Set에 요소가 없는지 알 수 있어요.

var numbers = <int>{};
print(numbers.isEmpty); // true
print(numbers.length); // 0

var fruits = {'사과', '파인애플', '오렌지'};
print(fruits.isEmpty); // false

.isNotEmpty( )를 통해 List 또는 Set에 요소가 있는지 알 수 있어요.

var numbers = <int>{};
print(numbers.isNotEmpty); // false

var fruits = {'사과', '파인애플', '오렌지'};
print(fruits.isNotEmpty); // true

.add( ), addAll( )을 통해 요소를 추가할 수 있어요.

var fruits = {'사과', '파인애플', '오렌지'};
fruits.add('복숭아');
print(fruits); // {사과, 파인애플, 오렌지, 복숭아}

fruits.addAll({'포도', '귤'});
print(fruits); // {사과, 파인애플, 오렌지, 복숭아, 포도, 귤}

final additionalFruits = {'샤인머스켓', '수박'};
fruits.addAll(additionalFruits);
print(fruits); // {사과, 파인애플, 오렌지, 복숭아, 포도, 귤, 샤인머스켓, 수박}

.remove( ), .removeAt( )를 통해 요소를 삭제할 수 있어요.(단, Set에는 Index개념이 없기 때문에 .removeAt( ) 사용불가

var fruits = {'사과', '파인애플', '오렌지'};
fruits.remove('파인애플');
print(fruits); // {사과, 오렌지}

.contains( ), containsAll( )을 통해 특정 요소가 있는지 알 수 있어요.

var fruits = ['사과', '파인애플', '오렌지'];
fruits.remove('파인애플');
print(fruits); // [사과, 오렌지]

var appleIndex = fruits.indexOf('사과');
fruits.removeAt(appleIndex);
print(fruits); // [오렌지]

TIP💡 List는 [ ], Set은 { }로 표현해줍니다.

3. Map

키(Key)와 값(Value)이 묶인 하나의 쌍으로 이루어진 형태

  • 선언방법
    • Map<key 타입, value 타입> 변수 이름 = {key: value};
    Map<String, String> people = {'Alice': 'Teacher', 'Bob': 'Student'};
    • 변수 이름 = {key: value};
    var people = {'Alice': 'Teacher', 'Bob': 'Student'};
    • Map 요소에 변동이 없는 경우 final이나 const로 선언이 가능해요!
    final people = {'Alice': 'Teacher', 'Bob': 'Student'};
    const animals = {'Dog': 3, 'Cat': 5};
  • Map의 특징
    - 키와 값은 타입이 같아야 합니다.
    ```dart
    Map<String, int> people = {'Alice': 25, 'Bob': 'Teacher'};
    // Error: A value of type 'String' can't be assigned to a variable of type 'int'.
    ```
    - 키와 값을 서로 다른 타입으로 구성할 수 있어요.
    ```dart
    Map<String, int> people = {'Alice': 25, 'Bob': 30};
    ```
    - 키는 중복될 수 없지만, 값은 중복될 수 있어요.
    ```dart
    Map<String, int> people = {'Alice': 25, 'Bob': 25, 'Alice': 23};
    print(people); // {Alice: 23, Bob: 25}
    ```

    TIP💡 키가 중복되면 나중에 선언된 키의 값이 저장됩니다.

Map 더 알아보기
.length를 통해 요소의 개수를 구할 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
print(people.length); // 2

.isEmpty를 통해 Map 에 요소가 없는지 (Map 이 비어있는지) 알 수 있어요.

var names = {};
print(names.isEmpty); // true
print(names.length); // 0

var people = {'Alice': 25, 'Bob': 30};
print(people.isEmpty); // false

TIP💡 Map도 List, Set과 같이 isEmpty가 있으면 isNotEmpty도 있습니다!
.[변수 이름][키 이름]] 를 통해 값을 검색할 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
print(people['Alice']); // 25

TIP💡 Map에 없는 키를 넣으면 null이 반환됩니다.

.[변수 이름][키 이름]] = [값]; 을 통해 키의 값을 수정할 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
people['Alice'] = 28;
print(people); // {Alice: 28, Bob: 30}
print(people['Alice']); // 28

.[변수 이름][키 이름]] = [값]; 을 통해 새로운 키와 값의 쌍을 추가할 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
people['Charlie'] = 35;
print(people); // {Alice: 25, Bob: 30, Charlie: 35}

.remove()를 통해 요소를 삭제할 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
people.remove('Bob');
print(people); // {Alice: 25}
print(people['Bob']); // null

.containsKey()를 통해 특정 요소가 있는지 알 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
print(people.containsKey('Alice')); // true
print(people.containsKey('Paul')); // false

.keys를 통해 모든 키들을 알 수 있어요.

Map<String, int> people = {'Alice': 25, 'Bob': 30};
print(people.keys); // (Alice, Bob)

.values를 통해 모든 값들을 알 수 있어요.

var students = {'Alice': 25, 'Bob': 30};
print(students.values); // (25, 30)

var teachers = {'Paul': 35, 'Henry': 37, 'Bella': 35};
print(teachers.values); // (35, 37, 35)
profile
우주를 항해하는 여행자

0개의 댓글