Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

removewhere
hashmap
dart
communitycreator

What is the HashMap.removeWhere method in Dart?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Dart, the removeWhere method is used to remove all the entries that satisfy the provided test condition.

Note: HashMap.removeWhere is an implementation of MapMap contains a list of key-value pairs as an element. based on a hash table. Read more about HashMap here.

Syntax

void removeWhere( bool test(K key,V value) )

Parameter

This method takes a test function with two arguments, keys and values. It returns a boolean value. This method is invoked for each entry of the map.

The removeWhere method iterates the map and invokes the test function. If the test function returns true, the current entry is removed from the map.

Return value

This method doesn’t return any value.

Example

The code below demonstrates how to use the removeWhere method:

import 'dart:collection';
void main() {
//create a new hashmap which can have string type as key, and int type as value
HashMap map = new HashMap<String, int>();
// add three entries to the map
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
print('The map is $map');
// Remove the entry with odd value
map.removeWhere((key, value){
return value % 2 != 0;
});
print('The map is $map');
}
Using "removeWhere" method

Explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new HashMap object—map.

  • Lines 7–9: We add three new entries to the map. Due to this, the map now is {one: 1, two: 2, three: 3}.

  • Line 14: We use the removeWhere method with a test function as an argument. The test function returns true if the value is odd number. In our code, the key one and three have an odd value. Hence, those entries are removed from the map. After we remove the odd value entries, the map is {two:2}.

RELATED TAGS

removewhere
hashmap
dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring