Dart 编程中的映射
Maps是非常重要的数据结构,因为它们允许我们将键映射到某些特定的值,然后我们可以从键中获取值。
在Dart中,我们可以使用不同类型的映射。这些主要是-
哈希表
链接哈希映射
树状图
在大多数情况下,我们使用LinkedHashMap,因为它很容易创建和使用。
让我们在dart中创建一个简单的映射。
示例
考虑下面显示的例子-
void main() {
var colors = new Map();
print(colors);
}在上面的示例中,我们创建了一个空映射,然后将其打印出来。需要注意的是,当我们使用Map()构造函数创建映射时,它会创建一个LinkedHashMap。
LinkedHashMap与HashMap的不同之处在于它保留了我们将键插入其中的顺序。
输出结果
{}现在,让我们尝试将一些键值对添加到我们的颜色映射中。
示例
考虑下面显示的例子-
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
print(colors);
}键位于方括号内,我们要分配给这些键的值位于表达式的右侧。
输出结果
{blue: true, red: false, green: false, yellow: true}应该注意的是,当我们打印映射时,我们插入键的顺序是保持不变的。此外,映射中的所有键都必须具有相同的数据类型并不重要。
示例
考虑下面显示的例子-
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg"; //带有字符串值的int键
print(colors);
}在Dart中,拥有动态键和值是完全没问题的。
输出结果
{blue: true, red: false, green: false, yellow: true, 1: omg}现在让我们看看我们可以在映射上使用的一些属性。
示例
考虑下面显示的例子-
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";
print(colors['blue']); //访问特定密钥
print(colors.length); //检查映射中存在的键值对的数量
print(colors.isEmpty); //检查映射是否为空
print(colors.keys); //打印映射中存在的所有键
print(colors);
}输出结果true
5
false
(blue, red, green, yellow, 1)
{blue: true, red: false, green: false, yellow: true, 1: omg}我们还可以使用for-in循环遍历映射中存在的键和值。
示例
考虑下面显示的例子-
void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";void main() {
var colors = new Map();
colors['blue'] = true;
colors['red'] = false;
colors['green'] = false;
colors['yellow'] = true;
colors[1] = "omg";
print(" ---- Keys ---- ");
for(var key in colors.keys){
print(key);
}
print(" ---- Values ---- ");
for(var value in colors.values){
print(value);
}
}
print(" ---- Keys ---- ");
for(var key in colors.keys){
print(key);
}
print(" ---- Values ---- ");
for(var value in colors.values){
print(value);
}
}输出结果---- Keys ---- blue red green yellow 1 ---- Values ---- true false false true omg