Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator
retainwhere

What is List retainWhere() in Dart?

Maria Elijah

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.

The retainWhere() method removes all items from the list that fail to satisfy the specified condition.

Syntax

void retainWhere (
bool test(
E element
)
)

Parameter

This function takes element as a parameter and removes the rest of the items that do not specify the condition.

Return type

It returns nothing, so its return type is void.

Code

The following code shows how to use the method retainWhere() in Dart:

void main(){
  List numbers = [2, 6, 23, 14, 34, 8, 12, 57, 41, 1, 6];
  print('Original list before removing elements: ${numbers}');
  // Using retainWhere()
  // keep items greater than 10
  // and remove the rest of the items.
  numbers.retainWhere((item) => item > 10);
  // Display result
  print(' The new list after removing elements: ${numbers}');

  // Creating list
  List<String> names = ['Maria', 'Elizabeth', 'David', 'Elisa', 'Naomi', 'John', 'Joe'];
  print('Original list before removing elements: ${names}');
  // Using retainWhere()
  // keep items  whose length is greater than  or equal to 5
  // and remove the rest of the items.
  names.retainWhere((item) => item.length >= 5);
  //Display result
  print(' The new list after removing elements: ${names}');
}

Explanation

  • Line 2: We create the list of numbers and initialize it.
  • Line 7: We use retainWhere(), which keeps items greater than 10 and removes the rest of the items.
  • Line 8: We display the results.
  • Line 12: We create the list of string name and initialize it.
  • Line 17: We use retainWhere(), which keeps items whose length is greater than or equal to 5 and removes the rest of the items.
  • Line 19: We display the results.

RELATED TAGS

dart
communitycreator
retainwhere

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