×

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 Important Concepts

1. Anything placed in a variable is an object, and an object is an instance of a class. Numbers, functions, and null are all objects in Dart, and all these...

3 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

Dart Types of Functions

Functions are the set of statements intended to perform a specific task. They accept some input from the user, perform the specified computation and generate the output. They are very...

4 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.

Type System in Dart

Dart language is a type safety enabled language that uses static and dynamic type checking to match the value of the variable with its data type at the compile-time. This...

4 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.

Typedef in Dart

In Dart, typedef is used to generate a function type that we can use as a type annotation for declaring variables and return types of the function type. An alias...

4 minutes read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 minutes read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

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 Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart Booleans

Booleans Dart has a data type named ‘bool’ to represent Boolean values : true and false, which are compile-time constants. ‘True’ or ‘False’ cannot be assigned with values 1 or 0. Example, bool...

1 minute read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

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 Iterable

Iterable is a collection of elements that are accessed sequentially. These elements are accessible using the iterator getter and stepping through the values using this getter. Let us understand the setting...

6 minutes read.

Dart Arithmetic Operators

Arithmetic Operators comprises of all the operators that are used to perform arithmetic operations such as addition, subtraction, multiplication, division, etc. They are binary operators that work upon two operands. Consider A...

2 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 Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute 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.