Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashset
dart
contains
communitycreator

How to check if the LinkedHashSet contains an element in Dart

Programming Bytes

Overview

The contains method checks if the LinkedHashSet contains an element.

Syntax

bool contains (Object element)

Argument

The element to be checked is passed as an argument.

Return value

This method returns true if the passed element is present in the LinkedHashSet. Otherwise, it returns false.

A LinkedHashSet is a set of objects that contains unique elements and maintains the insertion of the elements.

Code

The code below demonstrates how the contains method checks if the LinkedHashSet contains an element:

import 'dart:collection';
void main() {
  //create a new LinkedHashSet which can have int type elements
  LinkedHashSet set = new LinkedHashSet<int>();

  // add five elements to the set
  set.add(1);
  set.add(2);
  set.add(3);

  print('The set is $set');

  // check if element contians 3
  print('set.contains(3) : ${set.contains(3)}');

  // check if element contians 5
  print('set.contains(5) : ${set.contains(5)}');
}
Using the contains method

Code explanation

  • Line 1: We import the collection library.

  • Line 4: We create a new LinkedHashSet object named set. We pass a compare function as an argument. This function maintains the set elements’ order. In our case, the compare function organizes the elements in descending order.

  • Lines 7–9: We add three new elements to the set. Now, the set is {1,2,3}.

  • Line 14: We use the contains method to check if the element 3 is present in the set. Since the element is present, true is returned.

  • Line 17: We use the contains method to check if the element 5 is present in the set. Since the element is not present, false is returned.

RELATED TAGS

linkedhashset
dart
contains
communitycreator
RELATED COURSES

View all Courses

Keep Exploring