import 'dart:io';
void main() {
var li = [3, 2, 1];
print("[1] first is ${li.first}");
print("[2] last is ${li.last}");
li.insert(0, 4);
print("[3] after add one value: $li");
li.sort((a, b) => a.compareTo(b));
print("[4] sorted list is $li");
// empty 생성자를 사용해 빈 리스트 생성
final myList = List<int>.empty(growable: true);
myList.addAll([5, 6, 7]);
print("[5] growable list is $myList");
myList.remove(7);
print("[6] seven value is removed: $myList");
myList.add(7);
print("[7] seven value is added: $myList");
myList.removeAt(2);
print("[8] seven value is removed again by index: $myList");
myList.add(7);
print("[9] seven value is added again: $myList");
print("[10] Is seven value contained? ${myList.contains(7)}");
// list iteration
print("[11] sum of all list values: ${myList.reduce((a, b) => a += b)}");
print("[12] double every value in list: ${myList.map((e) => e * 2)}");
num total1 = myList.fold(0, (previousValue, element) => previousValue + element);
print("[13] using fold method with initialValue 0: $total1");
num total2 = myList.fold(1, (previousValue, element) => previousValue + element);
print("[14] using fold method with initialValue 1: $total2");
// 채워지는 fill이 전부 같은 객체여도 이슈 있음 (원시 타입은 이슈 없음)
// 디폴트가 Fixed-length list
var someList = List.filled(3, 1);
print("[15-1] someList is $someList");
print("[15-2] using foreach: >>>");
someList.forEach(stdout.write);
print("\n");
// list collection if & for forms
var otherList = [for (int i = 1; i<10; i++) i];
print("[16] otherList is $otherList");
var evenList = [for (var i in otherList) if (i % 2 == 0) i];
print("[17] evenList is $evenList");
// unique elements
List duplicateList = <int>[1, 1, 1, 2, 2, 3, 3, 4, 5];
var uniqueList = duplicateList.toSet().toList();
print("[18] uniqueList is $uniqueList");
// filter list
var intList = <int>[-1, 3, 2, 0, 1, -3, 4, 3, 5];
var positiveValue = intList.where((element) => element > 0);
print("[19-1] positiveValue is $positiveValue");
print("[19-2] positiveValue type is ${positiveValue.runtimeType}");
var positiveValsList = positiveValue.toList();
print("[20] positiveValsList is $positiveValsList");
List<String> words = <String>["wolf", "sky", "falcon", "cloud", "wood", "oak"];
var neoWords = words.where((element) => element.length == 3);
print("[21] 3 length word is $neoWords");
var wStartWord1 = words.firstWhere((element) => element.startsWith('w'));
print("[22-1] begin with 'w' word is $wStartWord1. (first to last iteration)");
var wStartWord2 = words.lastWhere((element) => element.startsWith('w'));
print("[22-2] begin with 'w' word is $wStartWord2. (last to first iteration)");
// list map
// generate 생성자의 index는 0부터 시작
var powList = List<int>.generate(10, (index) => index + 1, growable: false).map((e) => e * e);
print("[23] powList is $powList");
bool evenExist = powList.every((element) => (element % 2 == 0));
if (evenExist) {print("[24] all values are even.");}
else {print("[24] not all values are even.");}
// list partitions
var takeFive = List<int>.generate(6, (index) => index).skip(1);
print("[25-1] first element was out: $takeFive");
print("[25-1] takeFive type is ${takeFive.runtimeType}");
// 2D lists
int row = 5, col = 2;
var twoDList1 = List.generate(row, (index) => List.filled(col, 0));
print("[26] twoDList1 is $twoDList1");
var twoDList2 = List.generate(row, (index) => List.generate(col, (index) => null));
print("[27] twoDList2 is $twoDList2");
var twoDList3 = List<List>.generate(row, (index) => List<dynamic>.generate(col, (index) => 'none'));
print("[28] twoDList3 is $twoDList3");
var twoDList4 = [
for (int r = 0; r < row; r++) [for (int c = 0; c < col; c++) 'dummy']
];
print("[29] twoDList4 is $twoDList4");
List<List<int>> twoDList5 =
[ [1, 1], [1, 1], [1, 1], [1, 1], [1, 1] ];
print("[30] twoDList5 is $twoDList5");
// cascade notation
// .. (dot dot) 사용해 동일 객체의 함수 호출, 필드 접근을 순서대로 실행 가능
// 객체 하나의 여러 메서드를 호출할 때 객체 이름 생략 가능
// 과정에서 리턴값은 무시
var mixList = List<dynamic>.generate(10, (index) => index + 1, growable: true)
..add('string')
..add(0.1);
print("[31] using cascade notation: $mixList");
// 결과
[1] first is 3
[2] last is 1
[3] after add one value: [4, 3, 2, 1]
[4] sorted list is [1, 2, 3, 4]
[5] growable list is [5, 6, 7]
[6] seven value is removed: [5, 6]
[7] seven value is added: [5, 6, 7]
[8] seven value is removed again by index: [5, 6]
[9] seven value is added again: [5, 6, 7]
[10] Is seven value contained? true
[11] sum of all list values: 18
[12] double every value in list: (10, 12, 14)
[13] using fold method with initialValue 0: 18
[14] using fold method with initialValue 1: 19
[15-1] someList is [1, 1, 1]
[15-2] using foreach: >>>
111
[16] otherList is [1, 2, 3, 4, 5, 6, 7, 8, 9]
[17] evenList is [2, 4, 6, 8]
[18] uniqueList is [1, 2, 3, 4, 5]
[19-1] positiveValue is (3, 2, 1, 4, 3, 5)
[19-2] positiveValue type is WhereIterable<int>
[20] positiveValsList is [3, 2, 1, 4, 3, 5]
[21] 3 length word is (sky, oak)
[22-1] begin with 'w' word is wolf. (first to last iteration)
[22-2] begin with 'w' word is wood. (last to first iteration)
[23] powList is (1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
[24] not all values are even.
[25-1] first element was out: (1, 2, 3, 4, 5)
[25-1] takeFive type is SubListIterable<int>
[26] twoDList1 is [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
[27] twoDList2 is [[null, null], [null, null], [null, null], [null, null], [null, null]]
[28] twoDList3 is [[none, none], [none, none], [none, none], [none, none], [none, none]]
[29] twoDList4 is [[dummy, dummy], [dummy, dummy], [dummy, dummy], [dummy, dummy], [dummy, dummy]]
[30] twoDList5 is [[1, 1], [1, 1], [1, 1], [1, 1], [1, 1]]
[31] using syntactic sugar: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, string, 0.1]
// using spread operator
List l1 = [1, 2, 3];
List l2 = [0, ...l1];
print("l1 is $l1, (length: ${l1.length})");
print("l2 is $l2, (length: ${l2.length})");
// 결과
l1 is [1, 2, 3], (length: 3)
l2 is [0, 1, 2, 3], (length: 4)
// 정수 리스트를 받아 평균을 내고
// 평균값 보다 적은 리스트를 생성해
// 0 index에는 평균값을 담아 반환
void main(List<String> args) {
List<dynamic> underAvg(List<int> nums) {
int sum = 0;
double avg = 0;
for (int n in nums) {sum += n;}
avg = (sum/nums.length);
return [for (int n in nums) if (n < avg) n]
..insert(0, avg);
}
var li = [1, 2, 3, 4, 5, 6];
print("[1] in nums is $li");
print("[2] average is ${underAvg(li).first}");
print("[3] under average value is ${underAvg(li).skip(1)}");
}
// 결과
[1] in nums is [1, 2, 3, 4, 5, 6]
[2] average is 3.5
[3] under average value is (1, 2, 3)
// collection for 사용
var liRaw = [1, 2, 3];
var sum = 0;
for (int i in liRaw) {sum += i;}
var liAdded1 = [sum, ...liRaw];
var liAdded2 = [liRaw.length, for (int i in liRaw) i];
print("sum: ${liAdded1[0]} / all: $liAdded1");
print("length: ${liAdded2[0]} / all: $liAdded2");
// 결과
sum: 6 / all: [6, 1, 2, 3]
length: 3 / all: [3, 1, 2, 3]
void main(List<String> args) {
const someList = [1, 'apple', 'cherry', 'banana', 2, 3];
var sum = 0;
List<String> liStr = [];
for (var e in someList) {
switch (e.runtimeType) {
case int:
sum += e as int;
case String:
liStr.add(e as String);
default:
continue;
}
}
print("sum is $sum");
print("all string is $liStr");
}
// 결과
sum is 6
all string is [apple, cherry, banana]
void main(List<String> args) {
List allList = [1, 'list', 10.1, '리스트'];
print("[0] allList: $allList");
// sublist 함수 사용
var subList1 = allList.sublist(0, 2);
print("[1] 0 - 1 sublist: $subList1");
var subList2 = allList.sublist(2, allList.length);
print("[2] 2 - 3 sublist: $subList2");
var subList3 = allList.sublist(2);
print("[3] 2 - end sublist: $subList3");
List anyLenStrList = ['apple', 'banana', 'kiwi', 'melon', 'mango'];
List fourLen = [];
for (String s in anyLenStrList) {
if (s.length == 4) {
fourLen.add(s);
}
}
print("[4] Length of 4 is $fourLen");
fourLen.clear();
fourLen.addAll(anyLenStrList.where((n) => n.length == 4));
print("[5] Length of 4 is $fourLen");
print("[6] Is 'kiwi' is exist? ${anyLenStrList.contains('kiwi')}");
// 자주 쓰는 컬렉션 처리 메서드 기억하기
// map() -> map은 트랜스포머 메서드로 기억
// 각각의 모든 원소에 대해 처리후 반환
// It accepts a collection,
// transforms it into something else based on the conditions
// and returns a new collection.
// where() -> filter() 메서드로 기억
// 조건에 맞는 원소를 반환
// It accepts a collection of items and a condition,
// filters the collection based on the condition and
// returns a new collection of filtered items.
// reduce() -> 요소 두 개씩 조건 처리
// 또 다시 이전 원소(조건 처리된)와 다음 원소를 조건 처리
// 집합 끝까지 진행 후 하나의 결과 반환
// (= 원소를 하나씩 꺼내 특정 조건 처리된 누적 값 반환)
}
// 결과
[0] allList: [1, list, 10.1, 리스트]
[1] 0 - 1 sublist: [1, list]
[2] 2 - 3 sublist: [10.1, 리스트]
[3] 2 - end sublist: [10.1, 리스트]
[4] Length of 4 is [kiwi]
[5] Length of 4 is [kiwi]
[6] Is 'kiwi' is exist? true
void main(List<String> args) {
List<Map<String, int>> scores = [
{'jon': 80},
{'david': 60},
{'kelly': 70}
];
// forEach는 callback의 특성이 있다.
var scoreSum = 0;
for (var score in scores) {
score.forEach((name, score) {
scoreSum += score;
});
}
print("[1] toal score is $scoreSum");
}
// 결과
[1] evenList: [2, 4]
[2] toal score is 210
// 리스트 역순
// reverse a list
void main(List<String> args) {
//intialize a new list from iterable to the items of reversed order
List<int> orgList = [1, 2, 3];
var rList1 = List.from(orgList.reversed);
print("[1] reversed order: $rList1");
//Reverse Dart List with Reversed List as a new List and Saving Original #1
List<int> rList2 = [];
for (int i in orgList) {
rList2.insert(0, i);
}
print("[2] reversed order: $rList2");
// Reverse Dart List with Reversed List as a new List and Saving Original #2
List<int> rList3 = List.filled(orgList.length, 0);
for (int i = 0; i < orgList.length; i++) {
rList3[i] = orgList[orgList.length - 1 - i];
}
print("[3] reversed order: $rList3");
}
// 결과
[1] reversed order: [3, 2, 1]
[2] reversed order: [3, 2, 1]
[3] reversed order: [3, 2, 1]
void main(List<String> args) {
List<Map<String, dynamic>> lms = [
{'name': 'jon', 'age': 24, 'job': 'student', 'adult': false},
{'name': 'danny', 'age': 30, 'job': 'intern', 'adult': false},
{'name': 'sayaka', 'age': 19, 'job': 'student', 'adult': false}
];
var ageCondition = 20;
// map k, v를 읽어 특정 조건이면 또 다른 k의 v를 수정
// for (var lm in lms) {
// for (var key in lm.keys) {
// if (key == 'age' && lm[key] > ageCondition) lm['adult'] = true;
// }
// }
// simpler version
for (var lm in lms) {
if (lm['age'] > ageCondition) {
lm['adult'] = true;
}
}
for (int i=0; i<lms.length; i++){
print("[$i] result: ${lms[i].toString()}");
}
}
// 결과
[0] result: {name: jon, age: 24, job: student, adult: true}
[1] result: {name: danny, age: 30, job: intern, adult: true}
[2] result: {name: sayaka, age: 19, job: student, adult: false}
void main(List<String> args) {
// Iterate Over a Map
List<Map<String, dynamic>> gg = [
{'name': 'NewJeans', 'members': 5, 'iSFantastic': true},
{'name': 'Twice', 'members': 9, 'iSFantastic': true}
];
// The Map class has a forEach method that allows you to perform iteration.
for (var g in gg) {
g.forEach((key, value) {
print("key: $key, value: $value");
});
}
print('==============================');
// Map has a property named entries which returns an Iterable of entries.
for (var g in gg) {
Iterable<MapEntry<String, dynamic>> entry = g.entries;
for (var e in entry) {
print("key: ${e.key}, value: ${e.value}");
}
}
print('==============================');
// Dart's Iterable has iterator property.
// You can iterate using the Iterator by calling moveNext() to go to the next entry.
for (var g in gg) {
Iterator it = g.entries.iterator;
while (it.moveNext()) {
MapEntry<String, dynamic> entry = it.current;
print("key: ${entry.key}, value: ${entry.value}");
}
}
print('==============================');
}
// 결과
key: name, value: NewJeans
key: members, value: 5
key: iSFantastic, value: true
key: name, value: Twice
key: members, value: 9
key: iSFantastic, value: true
==============================
key: name, value: NewJeans
key: members, value: 5
key: iSFantastic, value: true
key: name, value: Twice
key: members, value: 9
key: iSFantastic, value: true
==============================
key: name, value: NewJeans
key: members, value: 5
key: iSFantastic, value: true
key: name, value: Twice
key: members, value: 9
key: iSFantastic, value: true
==============================
void main(List<String> args) {
// Count the Occurrences of Elements in a List
var vals = ['a', 'b', 'a', 'c', 'd', 'b', 'e', 'd', 'a', 'c', 'b'];
var occurrence = 0;
for (var val in vals) {
if (val == 'a') occurrence++;
}
print("[0] count 'a' is $occurrence");
occurrence = vals.where((element) => element == 'a').length;
print("[1] count 'a' is $occurrence");
var counter = <String, int>{};
for (var val in vals) {
counter.update(val, (count) => count + 1, ifAbsent: () => 1);
}
print("[2] output is $counter");
}
// 결과
[0] count 'a' is 3
[1] count 'a' is 3
[2] output is {a: 3, b: 3, c: 2, d: 2, e: 1}
import 'dart:convert';
void main(List<String> args) {
// 다양한 list 표현
List ages = [1, 2, 3];
print(ages.runtimeType);
List<int> agesInt = [1, 2, 3];
print(agesInt.runtimeType);
List anotherAges = <num>[1, 2, 3];
print(anotherAges.runtimeType);
List mixedAges = [1, 'two', 3, 1 + 3];
print(mixedAges.runtimeType);
// Fixed Length List
List fixedLs1 = List<int>.filled(3, 0);
print(fixedLs1);
List fixedLs2 = List<String>.empty(growable: true);
print(fixedLs2);
const jsonArray = '''
[{"text": "foo", "value": 1, "status": true},
{"text": "bar", "value": 2, "status": false}]
''';
final List<dynamic> dynamicList = jsonDecode(jsonArray);
final List<Map<String, dynamic>> fooData =
List.from(dynamicList.where((x) => x is Map && x['text'] == 'foo'));
print(fooData); // [{text: foo, value: 1, status: true}]
// Mutable And Immutable List
List namesMutable = ["Sam", "Elon", "Dan"];
const List namesImmutable = ["John", "Sally", "David"];
namesMutable[0] = 'Sammy';
print(namesMutable);
// namesImmutable[0] = ''; (not possible)
List one = [1];
List two = [1, 2];
print(one.single);
try {
print(two.single);
} catch (e) {
print(e);
}
List emptyList = [];
print(emptyList.isEmpty);
var intList1 = [10, 15, 20, 25, 30];
print("List before updation: $intList1");
intList1.replaceRange(0, 2, [1, 2]);
print("List after updation using replaceAll() function : $intList1");
var intList2 = [10, 20, 30, 40, 50];
print("List before removing element : $intList2");
intList2.remove(30);
print("List after removing element : $intList2");
var intList3 = [10, 20, 30, 40, 50];
print("List before removing element:$intList3");
intList3.removeLast();
print("List after removing last element:$intList3");
// Multiply All Value By 2 Of All List
var intListFrom = [10, 20, 30, 40, 50];
var intListTo = intListFrom.map((e) => e * 10);
print(intListTo);
// Note: Choose Lists if order matters.
// You can easily add items to the end.
// Searching can be slow when the List size is big.
}
// 결과
List<dynamic>
List<int>
List<num>
List<dynamic>
[0, 0, 0]
[]
[{text: foo, value: 1, status: true}]
[Sammy, Elon, Dan]
1
Bad state: Too many elements
true
List before updation: [10, 15, 20, 25, 30]
List after updation using replaceAll() function : [1, 2, 20, 25, 30]
List before removing element : [10, 20, 30, 40, 50]
List after removing element : [10, 20, 40, 50]
List before removing element:[10, 20, 30, 40, 50]
List after removing last element:[10, 20, 30, 40]
(100, 200, 300, 400, 500)
void main(List<String> args) {
List nums = [1, 2, 3, 4, 5];
List sum = [];
// lazy iterable로 map 안에 있는 익명 함수에 컬렉션 요소를 하나씩 전달
Iterable<int> newIterable = nums.map((e) {
sum.add(e);
return e;
});
print(sum);
print(newIterable);
// 결과: []
// (1, 2, 3, 4, 5)
// newIertable이 실행되기 전까지 map 안 바디는 실행되지 않는다.
// 이게 lazy의 의미
print('==============================');
print(newIterable);
print(sum);
// 이 경우에는 이터러블을 먼저 사용했기 때문에 map(() {})의 바디가
// 실행이 된다.
}
// 결과
[]
(1, 2, 3, 4, 5)
==============================
(1, 2, 3, 4, 5)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
void main(List<String> args) {
var ints01 = [1, 2, 3, 4];
List ints02 = <int>[1, 2, 3, 4];
List<int> ints03 = [1, 2, 3, 4];
print(ints01);
print(ints02);
print(ints03);
// Immutable list
final scores = [1, 2, 3, 4, 5];
// scores = []; // The final variables 'scores' can only be set once.
// To make a list truly immutable, you use the const instead of the final keyword
const immutableList = [1, 2, 3, 4, 5];
try {
immutableList.add(5);
} catch (e) {
print(e);
}
// Spreading list elements
var low = [1, 2, 3];
var high = [4, 5];
var lowHigh = [...low, ...high];
print(lowHigh);
// Collection if
bool male = true;
bool female = false;
List<String> members1 = [
if (male) "John",
if (female) "Kelly",
if (female) "Sally",
if (male) "Mike",
];
print("male: $members1");
male = false;
female = true;
List<String> members2 = [
if (male) "John",
if (female) "Kelly",
if (female) "Sally",
if (male) "Mike",
];
print("female: $members2");
var numbers = [1, 2, 3];
var newNums = [0, for (var number in numbers) number * 2];
print(newNums);
}
// 결과
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
Unsupported operation: Cannot add to an unmodifiable list
[1, 2, 3, 4, 5]
male: [John, Mike]
female: [Kelly, Sally]
[0, 2, 4, 6]
// Introduction to the Iterable<E> where() method
//
// The where() method returns a new iterable
// with all elements that satisfy a test.
void main(List<String> args) {
List<int> nums = [1, 2, 3, 4, 5];
var result = nums.where((e) => e > 3);
// The where() method returns an iterable object. Therefore, you see the () instead of [].
print("Bigger than 3 is $result");
print(result.runtimeType);
// If you want to convert an iterable object to a list, you can use the toList() method like this:
print("Bigger than 3 is ${result.toList()}");
}
// 결과
Bigger than 3 is (4, 5)
Bigger than 3 is [4, 5]
WhereIterable<int>
void main(List<String> args) {
var people = [
Person(name: 'Alice', age: 18),
Person(name: 'Bob', age: 16),
Person(name: 'John', age: 21),
Person(name: 'Peter', age: 23),
Person(name: 'David', age: 15),
];
var filtered = people.where((p) => p.age >= 18);
print("age >= 18: $filtered");
}
class Person {
String name = '';
int age = 0;
Person({required this.name, required this.age});
@override
String toString() => name;
}
// 결과
age >= 18: (Alice, John, Peter)
void main(List<String> args) {
const list = [1, 2, 3];
list.forEach((element) => print(element));
print('');
list.forEach((element) {
print(element);
});
print('');
list.forEach(print); // Dart will pass the argument implicitly
}
// 결과
1
2
3
1
2
3
1
2
3
void main(List<String> args) {
const list = [1, 2, 3];
final triples = list.map((e) => e * 3);
print(triples);
}
/*
map operator:
- take a collection
- transform all its items
- return a new collection
map is very powerful:
- apply any transformation we want with very little code
Iterable:
- collection of elements that can be accessed sequentially
Lazy Iterable:
- The anonymous function is not evaluated until the result is used
iterable.toList() will:
- compute all the items
- return them inside a List
summary
- Many collection methods return Iterables
- Use .toList() to convert to a List
*/
// 결과
(3, 6, 9)
void main(List<String> args) {
List<int> excludeValue = [1, 3, 5, 7, 9];
for (int i = 0; i < 10; i++) {
if (!excludeValue.contains(i)) {
print(i);
}
}
print('');
for (var i in excludeValue.where((value) => value > 5)) {
print(i);
}
}
// 결과
0
2
4
6
8
7
9
void main(List<String> args) {
var salesFigures = [
2150.71,
2200.50,
1500.25,
1100.55,
3255.55,
1223.60,
3321.33,
5533.20,
1202.50,
3455.61,
2111.20,
2335.90
];
var months = [
'January',
'Febryary',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
double sum = 0.0;
double highest = salesFigures[0];
double lowest = salesFigures[0];
for (var value in salesFigures) {
if (value > highest) {
highest = value;
}
if (value < lowest) {
lowest = value;
}
sum += value;
}
var highIndex = salesFigures.indexOf(highest);
var lowIndex = salesFigures.indexOf(lowest);
print(
'The highest salesFigures are ${highest.toStringAsFixed(2)} in ${months[highIndex]}');
print(
'The lowest salesFigures are ${lowest.toStringAsFixed(2)} in ${months[lowIndex]}');
print('The sum of salesFigures are ${sum.toStringAsFixed(2)}');
print(
'The avg of salesFigures are ${(sum / salesFigures.length).toStringAsFixed(2)}');
}
// 결과
The highest salesFigures are 5533.20 in August
The lowest salesFigures are 1100.55 in April
The sum of salesFigures are 29390.90
The avg of salesFigures are 2449.24
댓글 영역