Collection 메서드 편리하지만 잘 사용하기 넘 어려운 것...
Dart 공부하면서 자주 사용하는 메서드 이해하고 사용법 익히기!
참고한 문서
https://api.dart.dev/stable/3.5.4/index.html
Dart - Dart API docs
Welcome! Welcome to the Dart API reference documentation, covering the Dart core libraries. These include: dart:core: Core functionality such as strings, numbers, collections, errors, dates, and URIs. dart:io: I/O for non-web apps. dart:async: Functionalit
api.dart.dev
고차 함수(Higher-order Function)란
: 함수를 다루는 함수, Collection 타입의 데이터를 처리할 때 사용하는 메서드
map()
: Collection 타입의 데이터 각 요소에 명령을 적용한 새로운 Collection 타입의 데이터 반환
원본 데이터를 가공하지 않는다.
void main() {
List<String> colors = ['Red', 'Blue', 'Yellow'];
var whiteColors = colors.map((color) => 'White $color');
print(whiteColors);
}
결과
(White Red, White Blue, White Yellow)
map 내에서 여러 줄일 때는 중괄호로 묶고 return 값을 명시해야 한다.
void main() {
List<String> fruits = ['Apple', 'Banana', 'Peach'];
var coolFruits = fruits.map((fruit) {
if (fruit != 'Peach') {
return 'Cool $fruit';
} else {
return fruit;
}
});
}
결과
(Cool Apple, Cool Banana, Peach)
where()
: 특정 조건을 넣었을 때 참인 요소들만 필터링한 새로운 Collection 타입의 데이터 반환
원본 데이터를 가공하지 않는다. 조건식이 참이 요소가 없는 경우에는 빈 값을 반환한다.
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var upToFive = numbers.where((number) => number > 5);
print(upToFive);
}
결과
(6, 7, 8, 9, 10)
firstWhere()
: 특정 조건식에서 제일 처음의 참인 요소만 반환
원본 데이터를 가공하지 않는다. 조건식이 참인 요소가 없는 경우 오류 발생
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var upToFiveOnFirst = numbers.firstWhere((number) => number > 5);
print(upToFiveOnFirst);
}
결과
6
lastWhere()
: 특정 조건식에서 제일 마지막의 참인 요소만 반환
원본 데이터를 가공하지 않는다. 조건식이 참인 요소가 없는 경우 오류 발생
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var upToFiveOnLast = numbers.firstWhere((number) => number > 5);
print(upToFiveOnLast);
}
결과
10
reduce()
: Collection 타입의 데이터에 있는 요소를 하나의 값으로 결합한다.
Collection 타입의 같은 타입으로만 반환할 수 있다. Collection 타입의 데이터에 요소가 없는 경우에 오류 발생
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
var reduceNumber = numbers.firstWhere((a, b) => a + b);
print(reduceNumber);
}
결과
15
좀 더 자세한 설명을 하자면 a 값은 이전에 실행된 결과 값, b 는 numbers 의 다음 요소인 것이다.
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
var addNumbers = numbers.reduce((a, b) {
print('a : $a');
print('b : $b');
print('a + b: ${a + b}');
print('---------------');
return a + b;
});
print(addNumbers);
}
출력결과
a: 1
b : 2
a + b: 3
---------------
a : 3
b : 3
a + b: 6
---------------
a : 6
b : 4
a + b: 10
---------------
a : 10
b : 5
a + b: 15
---------------
15
fold()
: Collection 타입의 데이터에 있는 요소를 하나의 값으로 결합. reduce 와 다르게 초기값이 있음
Collection 타입의 데이터와 다른 타입으로도 반환이 가능함. Collection 타입의 데이터에 요소가 없어도 오류가 발생하지 않음
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
var addNumbers = numbers.fold(0, (a, b) {
print('a : $a');
print('b : $b');
print('a + b: ${a + b}');
print('---------------');
return a + b;
});
print(addNumbers);
}
출력결과
a : 0
b : 1
a + b: 1
---------------
a : 1
b : 2
a + b: 3
---------------
a : 3
b : 3
a + b: 6
---------------
a : 6
b : 4
a + b: 10
---------------
a : 10
b : 5
a + b: 15
---------------
15
any()
: Collection 타입의 데이터에 있는 요소 중 하나라도 주어진 조건을 만족하면 true 반환
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var anyNumber = numbers.any((number) => number > 5);
print(anyNumber);
}
결과
true
every()
: Collection 타입의 데이터에 있는 요소 모두가 주어진 조건을 만족하면 true 반환
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var everyNumber = numbers.every((number) => number > 5);
print(everyNumber);
}
결과
false
takeWhile()
: Collection 타입의 데이터에 있는 요소들을 주어진 조건에 넣었을 때 참이 되는 동안은 해당 요소들을 반환하고,
조건이 처음으로 거짓이 되는 순간부터의 요소를 무시한다.
void main() {
List<int> repeatNumbers = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
var result = repeatNumbers.takeWhile((num) => num < 4);
print(result);
}
결과
(1, 2, 3)
skipWhile()
: Collection 타입의 데이터에 있는 요소들을 주어진 조건에 넣었을 때 참이 되는 동안은 해당 요소들을 건너뛰고,
조건이 처음으로 거짓이 되는 순간부터의 요소들을 모두 반환한다.
void main() {
List<int> repeatNumbers = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5];
var result = repeatNumbers.skipWhile((num) => num < 4);
print(result);
}
결과
(4, 5, 1, 2, 3, 4, 5)
'언어 > Dart' 카테고리의 다른 글
JSON 다루기 (0) | 2024.12.02 |
---|---|
Dart 시작하기! (0) | 2024.10.08 |
댓글