Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile

DART2 Prima Plus - Tutorial 3 - MAP

5.00/5 (2 votes)
14 Jul 2018CPOL4 min read 11.6K   43  
Map class denotes a key and value container. I will showcase its various methods and properties.

Introduction

Within few weeks, I am writing the third article in DART2 Prima Plus series. As mentioned earlier, it is a new kid on the block, with feature addition and releases almost every week. I believe they are taking scrum methodology to heart.

In this article, I am going to discuss about Map class, which is similar to stl::Map in C++ and equivalent to System.Collection.Generic.Dictionary in C#. This thing I like about DART is, it's very similar to that of C++, when I code using it, it's like exploring your own roots.

Background

I am going to discuss the following properties and methods of Map class, this class is defined in package Dart:Core package, since DART is opensource, you can check its code in map.dart file. I am going to discuss the following properties provided by Map class. Definition and declaration are taken from the DART website

  • Constructors
    • Map()- Default constructor
    • Map.fromEnteries(Iterable<MapEntry<K, V>> entries) - Creates a new map and adds all entries
    • Map.fromIterables(Iterable<K> keys, Iterable<V> values) - Creates a Map instance associating the given keys to values
    • Map.unmodifiable(Map other) - Creates an unmodifiable hash based map containing the entries of other
  • Properties
    • entries => Iterable<MapEntry<K, V>> - The map entries of this
    • isEmpty => bool - Returns true if there is no key/value pair in the map
    • isNotEmpty => bool - Returns true if there is at least one key/value pair in the map
    • keys => Iterable<K> - The keys of this
    • length => int - The number of key/value pairs in the map
    • values => Iterable<V> - The values of this
  • Methods
    • addAll(Map<K, V> other) - Adds all key/value pairs of other to this map
    • addEntries(Iterable<MapEntry<K, V>> newEntries) - Adds all key/value pairs of newEntries to this map
    • clear() - Removes all pairs from the map
    • remove(Object key) - Removes key and its associated value, if present, from the map
    • removeWhere(bool predicate(K key, V value)) - Removes all entries of this map that satisfy the given predicate
  • Find and Replace
    • containsKey(Object key) - Returns true if this map contains the given key.
    • containsValue(Object value) - Returns true if this map contains the given value.
    • map<K2, V2>(MapEntry<K2, V2> f(K key, V value)) - Returns a new map where all entries of this map are transformed by the given f function.
    • update(K key, V update(V value), { V ifAbsent() }) - Updates the value for the provided key.
    • updateAll(V update(K key, V value)) - Updates all values.

Using the Code

Creation of Project

Till recently, I was manually creating the project, you can read more about manual project generation here. Now, there is a really nice project scaffold generator from DART team, which is StageHand. The installation steps are really very simple, in the terminal window, write the following command:

BAT
pub global activate stagehand

Once installed, when you run stagehand in command line, you will get the following information:

Image 1

Now for creating your project, use the following command:

C++
md dart3_map
cd dart3_map
stagehand console-full

Image 2

Here, first we are creating a project directory (md dart3_map) and then entering in a newly created directory (cd dart3_map) and in the end, creating a full console app using stagehand. Now, open the same folder in Visual Studio Code.

Constructors

In this part of task, I am discussing all ways to create map object, all this code is present in mapconstructor.dart under lib folder.

C#
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()}");
}
}

Image 3

Properties

I would be discussing properties supported by Map, all the code for the same are part of mapproperties.dart.

C#
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(","));
}

Image 4

Methods

In this area, I would be showcasing a method supported by Map, all code is given in mapmethods.dart.

C#
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 "));
}

Image 5

Find and Replace

In the last part of this article, I would be letting you know how to find and replace works in Map, all code present in mapfindandreplace.dart.

C++
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 "));
}

Image 6

With this, I come to the end of this article.

Points of Interest

Flutter Tutorial

  1. Flutter Getting Started: Tutorial #1
  2. Flutter Getting Started: Tutorial 2 - StateFulWidget
  3. Flutter Getting Started: Tutorial 3 Navigation

DART Series

  1. DART2 Prima Plus - Tutorial 1
  2. DART2 Prima Plus - Tutorial 2 - LIST

History

  • 14-July-2018: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)