void main(List<String> args) {
Map<int, String> m1 = {};
m1[1] = 'red';
m1[2] = 'green';
m1[3] = 'blue';
print(m1.values.last);
// Map은 중복 키를 허용하지 않기 때문에
// 내용 교체하려면 삭제 후 추가를 해야 한다.
// 그래서 .update 메서드를 제공한다.
m1.update(3, (value) => 'black', ifAbsent:() => 'newColor');
m1.update(4, (value) => 'black', ifAbsent:() => 'newColor');
print(m1);
}
// 결과
blue
{1: red, 2: green, 3: black, 4: newColor}
void main(List<String> args) {
Map<String, double> expenses = {'sun': 2000.0, 'mon': 1000.0, 'tue': 3000.0};
print("All keys of Map: ${expenses.keys}");
print("All values of Map: ${expenses.values}");
print("Is Map empty: ${expenses.isEmpty}");
print("Is Map not empty: ${expenses.isNotEmpty}");
print("Length of Map is: ${expenses.length}");
print("==============================");
// Looping Over Element Of Map
for (var ex in expenses.entries) {
print("Key: ${ex.key}, Value: ${ex.value}");
}
// Looping In Map Using For Each
expenses.forEach((key, value) => expenses.update(key, (value) => value + 1));
print("add plus one to Map's value is: $expenses");
}
// 결과
All keys of Map: (sun, mon, tue)
All values of Map: (2000.0, 1000.0, 3000.0)
Is Map empty: false
Is Map not empty: true
Length of Map is: 3
==============================
Key: sun, Value: 2000.0
Key: mon, Value: 1000.0
Key: tue, Value: 3000.0
add plus one to Map's value is: {sun: 2001.0, mon: 1001.0, tue: 3001.0}
void main(List<String> args) {
List vals = ['apply', 'ban', 'appoint', 'work'];
List meetCondition = vals
.where((item) => (item.toString().startsWith('a') && item.length < 6))
.toList();
print(meetCondition);
print("==============================");
// Student's exam marks
//
// format: Student ID, Gender, marks1, marks2
Map studentsMarks = {
'Jane': {
0002: ['female', 80, 90],
},
'John': {
0010: ['male', 75, 95],
},
'Ken': {
0109: ['male', 70, 55]
}
};
// print(studentsMarks['Jane'][0002]);
// total marks of male students
int totalMarksOfMaleStudents = 0;
for (var sEntry in studentsMarks.entries) {
for (var mEntry in sEntry.value.entries) {
if (mEntry.value[0] == 'male') {
totalMarksOfMaleStudents += mEntry.value[1] as int;
totalMarksOfMaleStudents += mEntry.value[2] as int;
}
}
}
print(totalMarksOfMaleStudents);
}
// 결과
[apply]
==============================
295
void main(List<String> args) {
bool condition = true;
try {
assert(condition != true, "condition is false.");
} catch (e) {
print(e);
}
print("==============================");
// How to Find Index Value Of List
var footballPlayers = ['Ronaldo', 'Messi', 'Neymar', 'Hazard'];
footballPlayers
.asMap()
.forEach((index, item) => print("index: $index, item: $item"));
print("==============================");
// Print Unicode Value of Each Character of String
String name = "John";
for (var codePoint in name.runes) {
print("Unicode of ${String.fromCharCode(codePoint)} is $codePoint.");
}
}
// 결과
'file:///C:/Users/SKTelecom/Documents/Dart_code/dart_application_1/bin/dart_application89.dart': Failed assertion: line 4 pos 12: 'condition != true': condition is false.
==============================
index: 0, item: Ronaldo
index: 1, item: Messi
index: 2, item: Neymar
index: 3, item: Hazard
==============================
Unicode of J is 74.
Unicode of o is 111.
Unicode of h is 104.
Unicode of n is 110.
void main(List<String> args) {
// Creating a map
var intMap01 = {"one": 1, "two": 2, "three": 3};
print(intMap01);
var intMap02 = <String, int>{"one": 1, "two": 2, "three": 3};
print(intMap02);
Map<String, int> intMap03 = {"one": 1, "two": 2, "three": 3};
print(intMap03);
Map intMap04 = <String, int>{"one": 1, "two": 2, "three": 3};
print(intMap04);
// Accessing elements from a map
print(intMap04['one']);
// Adding elements to a map
Map<String, int> numbers = {'one': 1, 'two': 2, 'three': 3};
numbers['four'] = 4;
print(numbers);
var totalValue = 0;
numbers.forEach((key, value) {
totalValue += value;
});
print(
"total of using reduce: ${numbers.values.reduce((value, element) => value + element)}");
print("total of using foreach: $totalValue");
// Checking for the existence of keys or values
print("Is key: one exist? ${numbers.containsKey('one')}");
print("Is value: 1 exist? ${numbers.containsValue(1)}");
}
// 결과
{one: 1, two: 2, three: 3}
{one: 1, two: 2, three: 3}
{one: 1, two: 2, three: 3}
{one: 1, two: 2, three: 3}
1
{one: 1, two: 2, three: 3, four: 4}
total of using reduce: 10
total of using foreach: 10
Is key: one exist? true
Is value: 1 exist? true
/*
You can use the entries property of a map.
To iterate over elements of the map,
you can iterate over the map.entries.
Each MapEntry object has two properties including key and value.
*/
void main(List<String> args) {
var numbers = {"one": 1, "two": 2, "three": 3};
for (var num in numbers.entries) {
print("${num.key}: ${num.value}");
}
}
// 결과
one: 1
two: 2
three: 3
// Dart map()
//
// map() is one of transformer.
void main(List<String> args) {
var nums = [1, 2, 3];
var newNums = getNewNums(nums);
print(newNums);
print("");
var anotherNums = (nums.map((e) => e + 1)).toList();
print(anotherNums);
}
List<int> getNewNums(List<int> nums) {
List<int> newNums = [];
for (var n in nums) {
newNums.add(n + 1);
}
return newNums;
}
// 결과
[2, 3, 4]
[2, 3, 4]
void main(List<String> args) {
// An iterable is a collection of items that can be accessed sequentially.
// List and sets are iterable, but maps aren't.
Map<String, dynamic> person = {'name': 'John', 'age': 36, 'height': 1.84};
for (var entry in person.entries) {
print("${entry.key}:, ${entry.value}");
}
}
// 결과
name:, John
age:, 36
height:, 1.84
void main(List<String> args) {
final ratings = [4.0, 4.5, 3.5];
final restaurant = {
'name': 'Pizza Mario',
'cuisine': 'Italian',
...{
if (ratings.length >= 3) 'ratings': ratings,
'isPopular': true,
}
};
print(restaurant);
}
// 결과
{name: Pizza Mario, cuisine: Italian, ratings: [4.0, 4.5, 3.5], isPopular: true}
void main(List<String> args) {
var restaurants = [
{
'name': 'Pizza Mario',
'cuisine': 'Italian',
'ratings': [5.0, 3.5, 4.5],
},
{
'name': 'Chez Anne',
'cuisine': 'French',
'ratings': [5.0, 4.5, 4.0],
},
{
'name': 'Navaratna',
'cuisine': 'Indian',
'ratings': [4.0, 4.5, 4.0],
},
];
for (var rest in restaurants) {
double sum = 0;
final ratings = rest['ratings'] as List<double>;
for (double r in ratings) {
sum += r;
}
rest['avgRatings'] = sum / rest.length;
}
print(restaurants);
}
// 결과
[{name: Pizza Mario, cuisine: Italian, ratings: [5.0, 3.5, 4.5], avgRatings: 4.333333333333333}, {name: Chez Anne, cuisine: French, ratings: [5.0, 4.5, 4.0], avgRatings: 4.5}, {name: Navaratna, cuisine: Indian, ratings: [4.0, 4.5, 4.0], avgRatings: 4.166666666666667}]
void main(List<String> args) {
const pizzaPrices = {'margherita': 5.5, 'pepperoni': 7.5, 'vegetarian': 6.5};
const order = ['margherita', 'pepperoni', 'pineapple'];
double sum = 0;
for (String o in order) {
if (pizzaPrices.containsKey(o)) {
sum += pizzaPrices[o] as double;
}
}
print(sum);
}
// 결과
13.0
void main(List<String> args) {
var user = {
'username': 'peter',
'password': 'peter123',
'role': 'admin',
'staffNr': 9911,
};
Map<String, dynamic> user2 = {};
var password = user['password'];
// print(password.length); // 이 경우 password의 타입이 object이므로 length 메소드를 호출할 수 없음
var password2 = user['password'] as String;
print(password2.length); // 그러나 String 형변환을 하면 length 메소드 호출 가능
// accessing values that do not exist
var ipAddress = user['ipAddress'];
print(ipAddress); // null
var ipAddress2 = user['ipAddress'];
if (ipAddress2 == null) {
print('The value is empty');
} else {
print(ipAddress2);
}
print('');
for (var entry in user.entries) {
print('${entry.key} : ${entry.value}');
}
}
/*
maps or dictionaries in other languages
collection of key-value pairs
username: peter
password: peter123
role: admin
staffNr: 9911
*/
// 결과
8
null
The value is empty
username : peter
password : peter123
role : admin
staffNr : 9911
import 'dart:math' as Math;
void main(List<String> args) {
var map1 = {
'student': 'Peter',
'mark': 40,
};
var map2 = {
'student': 'Paul',
'mark': 76,
};
var map3 = {
'student': 'James',
'mark': 89,
};
var marks = [map1, map2, map3];
double sumMarks = 0.0;
String lowestStudent = marks[0]['student'] as String;
int lowestMark = marks[0]['mark'] as int;
String highestStudent = marks[0]['student'] as String;
int highestMark = marks[0]['mark'] as int;
for (var mark in marks) {
sumMarks += mark['mark'] as int;
if (mark['mark'] as int < lowestMark) {
lowestMark = mark['mark'] as int;
lowestStudent = mark['student'] as String;
}
if (mark['mark'] as int > highestMark) {
highestMark = mark['mark'] as int;
highestStudent = mark['student'] as String;
}
}
print('The student with the highest mark is $highestStudent, $highestMark');
print('The student with the lowest mark is $lowestStudent, $lowestMark');
print(
'The avg of the marks is ${(sumMarks / marks.length).toStringAsFixed(2)}');
}
// 결과
The student with the highest mark is James, 89
The student with the lowest mark is Peter, 40
The avg of the marks is 68.33
댓글 영역