What is HashSet.take() in Dart?
Overview
The dart:collection library provides advanced collection support for the Dart language. The library contains the HashSet<E> class, which is an unordered hash-table-based implementation of the abstract Set<E> class. The HashSet<E> class contains the take() method.
What is the HashSet.take() method?
The take() method returns a lazy iterable of the first count number of elements from the hash set. count is an argument of the take() function.
Note:
HashSet<E>is a collection of unique elements that provides constant-timeadd,remove, andcontainsoperations.HashSet<E>does not have a specified iteration order. However, multiple iterations on the set produce the same element order.
The figure below illustrates how the take() method works:
Syntax
The syntax of the take() method is as follows:
Iterable<E> take(int count)
Parameters
The take() method takes an integer count as input. It can not be negative.
Return value
The take() method returns the first count number of elements as a lazy iterable.
We can get the collection items by going through the iterator until we see the count elements.
The returned iterable may contain fewer than count elements if the input collection contains fewer than count elements.
Code
The code below shows how the take() method works in Dart:
import 'dart:collection';void main() {var countrySet = HashSet<String>();countrySet.add("America");countrySet.add("Japan");countrySet.add("India");countrySet.add("UAE");print('Printing Set Elements');print(countrySet);var result = countrySet.take(3);print('Iterable of length 3 : $result');}
Explanation
-
Line 3: We create an instance of a
HashSetclass of typeString. -
Lines 5 to 8: We use the
add()method to add a few country names to the HashSet:"America","Japan","India", and"UAE". -
Line 13: We call the
take()method with thecountpassed as3. This returns an iterable of length3, and contains the first three elements of the hash set. -
Line 14: We use the
print()function of the core library to display the set elements and the result of thetake()method.