65.9K
CodeProject 正在变化。 阅读更多。
Home

DART2 Prima Plus - 第三课 - MAP

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2018年7月14日

CPOL

4分钟阅读

viewsIcon

12387

downloadIcon

77

Map 类表示一个键值对容器。我将展示它的各种方法和属性。

引言

几周之内,我就写了 DART2 Prima Plus 系列的第三篇文章。正如之前提到的,这是一个新生的事物,每周都有新功能添加和发布。我相信他们很认真地践行敏捷开发方法。

在这篇文章中,我将讨论 Map 类,它类似于 C++ 中的 stl::Map,以及 C# 中的 System.Collection.Generic.Dictionary。我喜欢 DART 的一点是,它与 C++ 非常相似,当我用它编写代码时,就像在探索自己的根源。

背景

我将讨论 Map 类的以下属性和方法,该类定义在 Dart:Core 包中。由于 DART 是开源的,您可以在 map.dart 文件中查看其代码。我将讨论 Map 类提供的以下属性。定义和声明摘自 DART 网站。

  • 构造函数
    • Map() - 默认构造函数
    • Map.fromEnteries(Iterable<MapEntry<K, V>> entries) - 创建一个新 Map 并添加所有 entries
    • Map.fromIterables(Iterable<K> keys, Iterable<V> values) - 创建一个 Map 实例,将给定的 keys 关联到 values
    • Map.unmodifiable(Map other) - 创建一个包含 other 中条目的不可修改的基于哈希的 Map。
  • 属性
    • entries => Iterable<MapEntry<K, V>> - 此 Map 的条目
    • isEmpty => bool - 如果 Map 中没有键值对,则返回 true
    • isNotEmpty => bool - 如果 Map 中至少有一个键值对,则返回 true
    • keys => Iterable<K> - 此 Map 的键
    • length => int - Map 中的键值对数量
    • values => Iterable<V> - 此 Map 的值
  • 方法
    • addAll(Map<K, V> other) - 将 other 中的所有键值对添加到此 Map。
    • addEntries(Iterable<MapEntry<K, V>> newEntries) - 将 newEntries 中的所有键值对添加到此 Map。
    • clear() - 从 Map 中移除所有条目
    • remove(Object key) - 如果 Map 中存在该键,则移除键及其关联的值。
    • removeWhere(bool predicate(K key, V value)) - 移除此 Map 中满足给定谓词的所有条目。
  • 查找和替换
    • containsKey(Object key) - 如果此 Map 包含给定键,则返回 true
    • containsValue(Object value) - 如果此 Map 包含给定值,则返回 true
    • map<K2, V2>(MapEntry<K2, V2> f(K key, V value)) - 返回一个新 Map,其中此 Map 的所有条目都通过给定的 f 函数进行转换。
    • update(K key, V update(V value), { V ifAbsent() }) - 更新提供键的值。
    • updateAll(V update(K key, V value)) - 更新所有值。

Using the Code

项目创建

直到最近,我都是手动创建项目,您可以在 这里 阅读更多关于手动项目生成的信息。现在,DART 团队提供了一个非常好的项目脚手架生成器,叫做 StageHand。安装步骤非常简单,在终端窗口中输入以下命令:

pub global activate stagehand

安装完成后,当您在命令行中运行 stagehand 时,您将看到以下信息:

现在,要创建您的项目,请使用以下命令:

md dart3_map
cd dart3_map
stagehand console-full

在这里,我们首先创建一个项目目录 (md dart3_map),然后进入新创建的目录 (cd dart3_map),最后使用 stagehand 创建一个完整的控制台应用程序。现在,在 Visual Studio Code 中打开同一个文件夹。

构造函数

在本部分任务中,我将讨论创建 map 对象的所有方法,所有这些代码都包含在 lib 文件夹下的 mapconstructor.dart 文件中。

void mapconstructor()
{
// Task 1.1 basic map creation
Map<int,String> mapCityVisited = new Map<int,String>();

// Seed some Initial values

mapCityVisited.putIfAbsent(1,()=> "Delhi");
mapCityVisited.putIfAbsent(2,()=> "London");
mapCityVisited.putIfAbsent(3,()=> "Vancouver");

print("Task 1.1 : map() -X-X-X-X-X-");
mapCityVisited.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 1.2 Map.from

Map<int,String> mapCityVisitedFrom = new Map.from(mapCityVisited);
print("Task 1.2 : Map.from -X-X-X-X-X-");
mapCityVisitedFrom.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 1.3 Map.fromEntries

List<MapEntry<int,String>> lstMapEntries = new List<MapEntry<int,String>> ();
lstMapEntries.add(new MapEntry<int,String>(1,"Richmond BC"));
lstMapEntries.add(new MapEntry<int,String>(2,"Burnaby BC"));
lstMapEntries.add(new MapEntry<int,String>(3,"Armstrong BC"));

Map<int,String> mapCitiesInBritishColumbia = new Map.fromEntries(lstMapEntries);
print("Task 1.3 : Map.fromEntries -X-X-X-X-X-");
mapCitiesInBritishColumbia.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 1.4 Map.fromIterables
//

List<int> lstInts = new List<int>.generate(3, (int index){return index+1;});
List<String> lstStrings = new List<String>.from(["Richmond BC","Burnaby BC","Armstrong BC"]);

Map<int,String> mapCitiesInBritishColumbia2 = new Map.fromIterables(lstInts, lstStrings);
print("Task 1.4 : Map.fromEntries -X-X-X-X-X-");
mapCitiesInBritishColumbia2.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 1.5 Map.unmodifiable

Map<int,String> mapCityVisitedFrom2 = new Map.unmodifiable(mapCityVisited);
print("Task 1.5 : Map.unmodifiable -X-X-X-X-X-");
try{

mapCityVisitedFrom2.putIfAbsent(4,()=>"Some New City");
}
catch(ex){
print("Unable to add new item in unmodifiable map : ${ex.toString()}");
}
}

属性

我将讨论 Map 支持的属性,所有相关代码都是 mapproperties.dart 的一部分。

void mapproperties()
{
Map<int,String> mapCityVisited = new Map<int,String>();

// Seed some Initial values

mapCityVisited.putIfAbsent(1,()=> "Delhi");
mapCityVisited.putIfAbsent(2,()=> "London");
mapCityVisited.putIfAbsent(3,()=> "Vancouver");

// Task 2.1 enteries

print("Task 2.1 : entries -X-X-X-X-X-");
mapCityVisited.entries.forEach((MapEntry<int,String> mapItem)=> 
                    print("key (${mapItem.key}) = ${mapItem.value} "));

// Task 2.2,2.3,2.4 isEmpty, isNotEmpty, length

print("Task 2.2,2.3,2.4: isEmpty, isNotEmpty, length -X-X-X-X-X-");
print("IsEmpty : ${mapCityVisited.isEmpty} , isNotEmpty : ${mapCityVisited.isNotEmpty}, 
                 length : ${mapCityVisited.length} ");

// Task 2.5,2.6 keys,values

print("Task 2.5,2.6 keys,values -X-X-X-X-X-");
print("All Keys : " + mapCityVisited.keys.join(","));
print("All Valuess : " + mapCityVisited.values.join(","));
}

方法

在这个区域,我将展示 Map 支持的一个方法,所有代码都包含在 mapmethods.dart 中。

void mapmethods(){

Map<int,String> mapCityVisited = new Map<int,String>();

// Seed some Initial values

mapCityVisited.putIfAbsent(1,()=> "Delhi");
mapCityVisited.putIfAbsent(2,()=> "London");
mapCityVisited.putIfAbsent(3,()=> "Vancouver");

// Task 3.1 addAll - fill the map using addAll

Map<int,String> mapCityVisited2 = new Map<int,String>();
mapCityVisited2.addAll(mapCityVisited);
print("Task 3.1 : addAll() -X-X-X-X-X-");
mapCityVisited2.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 3.2 addEntries - fill the map using iterable MapEntry

List<MapEntry<int,String>> lstMapEntries = new List<MapEntry<int,String>> ();
lstMapEntries.add(new MapEntry<int,String>(4,"Richmond BC"));
lstMapEntries.add(new MapEntry<int,String>(5,"Burnaby BC"));
lstMapEntries.add(new MapEntry<int,String>(6,"Armstrong BC"));

///
print("Task 3.2,3.3 : addEntries(),clear() -X-X-X-X-X-");

//Task 3.2 : Clear will remove all the items from map
mapCityVisited2.clear();
mapCityVisited2.addEntries(lstMapEntries);
mapCityVisited2.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 3.4 remove : remove the item based on the key
print("Task 3.4 : remove -X-X-X-X-X-");
print("removing key = 4 ");
mapCityVisited2.remove(4);
mapCityVisited2.forEach((int k,String v)=> print("key ($k) = $v "));

// Task 3.5 removeWhere : remove the item based on predicate or condition
print("Task 3.5 : removeWhere -X-X-X-X-X-");
mapCityVisited2.addAll(mapCityVisited);
print("Length of mapCityVisited2 is ${mapCityVisited2.length}, we will now remove all even keys");
mapCityVisited2.removeWhere((int key,String val){
return key%2==0;
});

mapCityVisited2.forEach((int k,String v)=> print("key ($k) = $v "));
}

查找和替换

在本文的最后部分,我将告诉您 Map 中的查找和替换是如何工作的,所有代码都包含在 mapfindandreplace.dart 中。

void mapfindandreplace(){

Map<int,String> mapCityVisited = new Map<int,String>();

// Seed some Initial values

mapCityVisited.putIfAbsent(1,()=> "Delhi");
mapCityVisited.putIfAbsent(2,()=> "London");
mapCityVisited.putIfAbsent(3,()=> "Vancouver");

//- Task 4.1 containKey

print("Task 4.1 : Does map contain key (1) : ${mapCityVisited.containsKey(1)}");
print("Task 4.1 : Does map contain key (4) : ${mapCityVisited.containsKey(4)}");

//- Task 4.2 containsValue

print("Task 4.2 : Does map contain value (Vancouver) : ${mapCityVisited.containsValue('Vancouver')}");
print("Task 4.2 : Does map contain value (Toronto) : ${mapCityVisited.containsValue('Toronto')}");

//- Task 4.3 map - convert one map to different type map
//- Here we convert map<int,string> to map<string,int> using map function

var mapCityVisited2 = mapCityVisited.map<String,int>((int key,String val)=>new MapEntry(val, key));
print("Task 4.3 : map() -X-X-X-X-X-");
mapCityVisited2.forEach((String k,int v)=> print("key ($k) = $v "));

//- Task 4.4 update, let update key 2 from London to berlin
// one good thing about update function is that, its has option to
// insert new item in case said key not present

mapCityVisited.update(2, (String val)=>"Berlin");
mapCityVisited.update(4,null ,ifAbsent: ()=>"London");
print("Task 4.4 : update() -X-X-X-X-X-");
mapCityVisited.forEach((int k,String v)=> print("key ($k) = $v "));

//- Task 4.5 updateAll,I will concatenate value with key

mapCityVisited.updateAll((int k,String v){ return "$v $k"; });
print("Task 4.5 : updateAll() -X-X-X-X-X-");
mapCityVisited.forEach((int k,String v)=> print("key ($k) = $v "));
}

至此,我完成了本篇文章。

关注点

Flutter 教程

  1. Flutter 入门:教程 #1
  2. Flutter 入门:教程 2 – StateFulWidget
  3. Flutter 入门:教程 3 导航

DART 系列

  1. DART2 Prima Plus - 教程 1
  2. DART2 Prima Plus - 第二课 - LIST

历史

  • 2018年7月14日:第一版
© . All rights reserved.