×

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type.

Every key can occur only once, while the values can be used multiple times.

                   var maps1 = { 1 : ‘one’, 2 : ‘two’, 3 : ‘three’ };

.length is used to get the number of key-value pairs in the map.

It is simple to add a new key-value pair to an existing map just like JavaScript,

                   Maps1[ 4 ] = ‘four’ ;

If you look for a key that isn’t in a map, then it returns null.

Methods of declaring a Dart Map

  1. Using Map literal
  2. Using Map constructor

Using Map Literals

In this method, the key - value pairs are enclosed within the curly braces ‘{  }’, separated by the commas.

Syntax :

var map_name = {key1 : val1, key2 : val2, key3 : val3, ….., keyn : valn} ;

Example :

Consider the following code in Dart to understand the maps implementation using map literals,

void main( )
{
    // declare and define a map named maps1
    var maps1 = { 1 : 'one' , 2 : 'two' , 3 : 'three' } ;
    
    // prints the values of map
    print ( maps1 ) ;
  
    // add new key-value pair to a map
    maps1[ 4 ] = 'four' ;
    print( maps1 ) ;
  
    // prints the length of map
    print( maps1.length ) ;
  
    // trying to print the value of key that exists
    print( maps1[ 3 ] ) ;
  
    // trying to print the value of key that doesn't exist
    print( maps1[ 5 ] ) ;
    
}

Output :

{1: one, 2: two, 3: three}
{1: one, 2: two, 3: three, 4: four}
4
three
null

Using Map( ) constructor

In this method, a map is declared using the map( ) constructor and then initialized with some values.

Syntax :

var map_name = new map(  ) ;  // declaring a map using a map( ) constructor
map_name[ key ] = value ; // initializing the keys with value

Example :

Consider the following code in Dart to understand the maps implementation using Map( ) constructor,

// using map constructor
void main( )
{
// declaring a map using a map( ) constructor
var maps1 = new Map( ) ;
// initializing keys with values
maps1[ 1 ] = 'one' ;
maps1[ 2 ] = 'two' ;
maps1[ 3 ] = 'three' ;
  
print( maps1 ) ;
}

Output :

{1: one, 2: two, 3: three}

Maps Properties

In order to use map properties in the code, one must include dart : core package library that has a class named Map containing the properties.

Here is the list of some of the most used properties :

PropertiesExplanation
KeysIt is used to get all the keys as an iterable object.
valuesIt is used to get a value against the key as an iterable object in a map.
LengthCalculates the number of key-value pairs in a map and returns the same.
isEmptyChecks if there are any key-value pairs in the map and accordingly returns true or false.
isNotEmptyChecks if there is at least one key-value pair in a map and accordingly returns true or false.

Consider the following code that lists all the properties of a Map.

Program

// using map constructor
void main( )
{
  // declaring a map using a map( ) constructor
  var maps1 = new Map( ) ;
  
  // initializing keys with values
  maps1[ 1 ] = 'one' ;
  maps1[ 2 ] = 'two' ;
  maps1[ 3 ] = 'three' ;
  
  print( maps1 );
  
  // using property keys. It prints all the keys of the given map
  print( "\n The keys of the map are : ${ maps1.keys } " ) ;
  
  // using property values. It prints all the values of the given map
  print( "\n The values of the map are : ${ maps1.values } " ) ;
  
  // using property length. It prints the number of key – value pairs in the map
  print( "\n The length of the map is : ${ maps1.length } \n " ) ;
  
  /// using property isEmpty. It returns true or false depending upon the 
  /// availability of key-value pair in the map
  print( maps1.isEmpty ) ;
  print( " \n " ) ;
  /// using property isNotEmpty. It returns true or false depending upon the 
  /// availability of key - value pair in the map
  print( maps1.isNotEmpty ) ;
}

Output

{1: one, 2: two, 3: three}
 The keys of the map are : (1, 2, 3) 
 The values of the map are : (one, two, three) 
 The length of the map is : 3 
 false
  
 true

Maps Functions

1. addAll( )

The addAll( ) function is used to add multiple key – value pairs to the list separated by a comma and enclosed within angular brackets ( < > ).

Implementation = Map.addAll( Map < Key, Value > other ) ;

Here, other denotes a key – value pair that returns a void type.

Program

void main( ) 
{   
  // assigning values to map 
  Map student = { 'name' : 'Yukta', 'Language' : 'Dart' } ;  
  
  // printing values of the map using string interpolation
  print( 'Map Values : ${ student }' ) ;   
     
  // using addAll( ) function to add the entire set of keys - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
}  

Output :

Map Values : {name: Yukta, Language: Dart}
Map after adding  keys - values : {name: Yukta, Language: Dart, Age: 19, College: IIT - D}

2. clear( )

The clear(  ) function is used to remove all key – value pairs from the map.

Implementation = Map.clear( ) ;

Program

void main( ) 
{   
  // assigning values to the map student
  Map student = { 'name' : 'Yukta', 'Language' : 'Dart' } ;  
  
  // printing values of the map using string interpolation
  print( ' Map Values : ${ student } ' ) ;   
     
  // using addAll( ) function to add the entire set of keys - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of the map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
  // using clear( ) function to clear the entire map
  student.clear( ) ;
  
  // printing the values of the map after clearing it
  print( ' Map after clearing  keys - values : ${ student } ' ) ;   
}

Output :

Map Values : {name: Yukta, Language: Dart} 
Map after adding  keys - values : {name: Yukta, Language: Dart, Age: 19, College: IIT - D} 
Map after clearing  keys - values : {}

As you can see clearly, nothing gets printed after clearing the map. This is because the clear( ) function cleared all the key - value pairs in the map.

3. remove ( )

The remove ( ) function is used to remove a single key and its associated value in the map.

Implementation = Map.remove( Object key ) ;

Here, Key refers to the specific entry to be deleted. It returns the value associated with that key.

Program

void main( ) 
{   
  // assigning values to the map student
  Map student = { 'name' : 'Yukta ', 'Language' : 'Dart' } ;  
  
  // printing values of map using string interpolation
  print( ' Map Values : ${ student } ' ) ;   
     
  // using addAll( ) function to add the entire set of key - value pairs to map
  student.addAll( { 'Age' : '19', 'College' : 'IIT - D' } ) ;  
  
  // printing the values of the map after adding the new key - value pairs
  print( ' Map after adding  keys - values : ${ student } ' ) ;   
  
  // using remove( ) function to remove the ‘ College ’ key from the map
  student.remove( 'College' );
  
  // printing the values of the map after removing the key ‘ College ’
  print( ' Map after removing College key : ${ student } ' ) ;   
}

Output:

Map Values : {name: Yukta , Language: Dart} 
Map after adding  keys - values : {name: Yukta , Language: Dart, Age: 19, College: IIT - D} 
Map after removing College key : {name: Yukta , Language: Dart, Age: 19}

4. forEach( )

The forEach( ) function is used to iterate over the entries of a map.

Implementation = Map.forEach( void f ( K key, V value) ) ;

Here, f (K key, V value) applies f to each key-value pair of the map. Calling f must not add or remove keys from the map


Related Topics

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart Tutorial

Dart is an open-source, structured programming language developed by Google. It is a high-level programming language that emerged in 2011, but its stable version emerged in 2017. It is largely used...

4 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart Concurrency

Dart concurrency allows us to run multiple or multiple components of a system at once. It issues several commands at once. Dart provides Isolates as a tool for performing compliance...

2 minutes read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Dart Loops

Looping refers to repeating or reusing the same lines of code repeatedly until a particular test condition evaluates to true. It is also known as iterating.  It is effectively used when...

4 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Dart Recursion

Recursion is one of the most important and interesting concepts in any programming language. It can be defined as a process in which a function calls itself directly or indirectly....

5 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.

Interfaces in Dart

An interface in Dart refers to the syntax or blueprint that any class must adhere to. It basically defines the array of methods available on the object. It provides the...

3 minutes read.

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 minutes read.

Dart Enumerations

Enumeration data type in Dart In simple terms, Enumerations are referred to as named constant values. Constant values are declared as enumerations using the ‘enum’ keyword.  Implementation =  enum enum_name {    ...

2 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart Variables

Variables are used to store the value of a particular data type referred to in the whole program by a name or identifier. They refer to a memory location as...

5 minutes read.

Dart Break and Continue

Loop statements are used to change the normal sequence of flow of the program. Dart supports two types of loop control statements: Break StatementContinue Statement Break Statement : The ‘ break ’ statement is...

4 minutes read.