Dart - Using Set, HashSet, LinkedHashSet, SplayTreeSet Examples

Set is a collection of values whose elements is always unique. There are three Set implementations in Dart: HashSet, LinkedHashSet and SplayTreeSet. In this tutorials, I'm going to tell you the difference between those Set implementations, the basic usages as well as list of available constructors, methods and properties.

Set

A collection of objects in which each object can occur only once. The data type of a Set can be integer, String, double, Object or any data type. There are three kinds of Set in Dart, differentiated by how the data stored which affects the iteration of the elements. By default, if you create a new Set, an instance of LinkedHashSet will be created.

HashSet

HashSet is an unordered hash-table based Set implementation. So, if you insert value A first and then insert another value B, when you iterate the elements, you may get value B first before value A. It allows null as element.

LinkedHashSet

In LinkedHashSet, data is stored based on insertion order. So, if you insert value A first and then insert another value B, when you iterate the elements, you will get value A first before value B. Like HashSet, it allows null element.

SplayTreeSet

SplayTreeSet is based on a self-balancing tree. Most operations can be done in O(log(n)). You cannot store non-comparable objects inclduing null. If you need to access certain elements more frequently than the others, it's beter to use SplayTreeSet as it can adjust the tree to move frequently accessed elements near the top of the tree.

Initialization

 LinkedHashSet set1 = new LinkedHashSet();

Add Value

Adding a new value to a Set is very simple, just use add method. If the value is duplicate of other elements, it will be ignored.

  set1.add('A');

Get Value at Index

To get the value at certain index, use elementAt method. Index begins at 0. If you enter a number bigger than maximum index (size of the Set - 1), it will throw error.

  set1.elementAt(2);

Get first element

To get the First Element, use first property.

  set1.first

Get Last Element

To get the last element, use last property.

  set1.last

Get Set Size

  set1.length

Check Value Existance

  set1.contains('A')

Check Value By Custom Logic

  bool anyValueNotD = set1.any((value) {
    return value != 'D';
  });

Remove Value

  set1.remove('B');

Remove Value with Custom Logic

In case you need to remove multiple values that meet certain criteria, use removeWhere method.

  set1.removeWhere((value) => value == 'A' || value == 'C');

Intersection Between Two Sets

To get values that present in two Sets, use intersection method.

  set1.intersection(set2);

Difference Between Two Sets

To get the values that present in a Set, but not in another Set, use difference method. The code below returns values that present in set1, but not present in set2. Values that present in set2 but not in set1 aren't included.

  set1.difference(set2);

Union of Two Sets

union method can be used to combined the values from two sets. The result is guaranteed to be unique

  set1.union(set2);

Iterate Through a Set

For looping through all values, use forEach method.

  set1.forEach((value) {
    print('Value: $value');
  });

Map a Set

It also has map method, you can map each value using your own logic

  var mappedSet = set1.map((value) {
    return 'mapped $value';
  });
  print('mappedSet: $mappedSet');

Reduce a Set

reduce method is provided as well. It accepts a function with the first parameter is the accumulator and the second parameter is the value of current element.

  var reduceResult = set1.reduce((acc, value) {
    return '$acc$value';
  });

Clear all Values

To remove all values, use clear method.

  set1.clear();

Convert Set to List

For converting Set to List, use .toList() method.

  List<String> listFromSet = set1.toList();

Usage Examples

Below is the usage examples of Set

  import 'dart:collection';
  
  import 'package:flutter_app/post.dart';
  
  main() {
    LinkedHashSet set1 = new LinkedHashSet<String>();
  //  SplayTreeSet set1 = new SplayTreeSet<String>(); // Uncomment to use SplayTreeSet
  //  HashSet set1 = new HashSet<String>(); // Uncomment to use HashSet
    HashSet set2 = new HashSet<String>();
  
    set1.add('A');
    set1.add('B');
    set1.add('C');
    set1.add('D');
    set1.add('E');
  
    print('set1: $set1');
    // Print result:
    //    set1: {A, B, C, D, E}
  
    print('Element at index 2: ${set1.elementAt(2)}');
    print('First element: ${set1.first}');
    print('Last element: ${set1.last}');
    // Print result:
    //    Element at index 2: C
    //    First element: A
    //    Last element: E
  
    // Adding the same value shouldn't affect the set
    set1.add('A');
    print('set1: $set1');
    // Print result:
    //    set1: {A, B, C, D, E}
  
    // Get number of elements
    print('Size of set: ${set1.length}');
    // Print result:
    //    Size of set: 5
  
    // Does it contain certain value?
    print('Contains A? ${set1.contains('A')}');
    // Print result:
    //    Contains A? true
  
    // Using [any] for custom logic
    // In this example, checks if the set contain any value other than D
    bool anyValueNotD = set1.any((value) {
      return value != 'D';
    });
    print('anyValueNotD? :$anyValueNotD');
    // Print result:
    //    anyValueNotD? :true
  
    set1.remove('B');
    print('set1: $set1');
    // Print result:
    //    set1: {A, C, D, E}
  
    set1.removeWhere((value) => value == 'A' || value == 'C');
    print('set1: $set1');
    // Print result:
    //    set1: {D, E}
  
    // Add values to set 2
    set2.add('E');
    set2.add('F');
  
    // Get intersection of set1 and set2
    print('intersection: ${set1.intersection(set2)}');
    // Print result:
    //    intersection: {E}
  
    // Get difference of set1 and set2
    print('difference: ${set1.difference(set2)}');
    // Print result:
    //    difference: {D}
  
    // Combine set1 with set2
    print('union: ${set1.union(set2)}');
    // Print result:
    //    union: {D, E, F}
  
    // Map every value
    var mappedSet = set1.map((value) {
      return 'mapped $value';
    });
    print('mappedSet: $mappedSet');
    // Print result:
    //    mappedSet: (mapped D, mapped E)
  
    // For each loop
    set1.forEach((value) {
      print('Value: $value');
    });
    // Print result:
    //    Value: D
    //    Value: E
  
    var reduceResult = set1.reduce((acc, value) {
      return '$acc$value';
    });
    print('reduceResult: $reduceResult');
    // Print result:
    //    reduceResult: DE
  
    // Convert set to list
    List<String> listFromSet = set1.toList();
    print('listFromSet: $listFromSet');
    // Print result:
    //    listFromSet: [D, E]
  
    // Print set as string
    print('set1 string: ${set1.toString()}');
    // Print result:
    //    set1 string: {D, E}
  
    // Clear set1
    set1.clear();
    print('set1: $set1');
    // Print result:
    //    set1: {}
  }

Constructors

This constructor list is for Set, but you can replace it with HashSet or LinkedHashSet because their constructors are very similar.

Name Parameters Description
Set ( {bool equals(E e1, E e2), int hashCode(E e), bool isValidKey(potentialKey)})

Create a set using the provided equals as equality.

Set.identity ( {bool equals(K key1, K key2), int hashCode(K key), bool isValidKey(potentialKey)}) Creates an identity-based set. Effectively a shorthand for: new HashSet(equals: identical, hashCode: identityHashCode)
Set.from (Iterable elements) Create a set containing all elements.
Set.of (Iterable<E> elements) Create a set containing all elements.

SplayTreeSet

SplayTreeSet has different constructors as listed below.

Name Parameters Description
SplayTreeSet ([int compare(E key1, E key2), bool isValidKey(potentialKey)])

Create a new SplayTreeSet with the given compare function.

SplayTreeSet.from (Iterable elements, [int compare(E key1, E key2), bool isValidKey(potentialKey)]) Create a SplayTreeSet containing all elements.
SplayTreeSet.of (Iterable<E> elements, [int compare(E key1, E key2), bool isValidKey(potentialKey)]) Creates a SplayTreeSet from elements.

Methods

Name Parameters Description
bool add (E value) Adds value to the set.
void addAll (Iterable<E> elements) Adds all elements to this Set.
bool any (bool test(E element)) Checks whether any element of this iterable satisfies test.
Iterable<R> cast<R> () Provides a view of this iterable as an iterable of R instances.
void clear () Removes all elements in the set.
bool contains (Object element) Returns true if the collection contains an element equal to element.
bool containsAll (Iterable<Object> other) Returns whether this Set contains all the elements of other.
Set<E> difference (Set<Object> other) Returns a new set with the elements of this that are not in other.
E elementAt (int index) Returns the indexth element.
bool every (bool test(E element)) Checks whether every element of this iterable satisfies test.
Iterable<T> expand<T> (Iterable<T> f(E element)) Expands each element of this Iterable into zero or more elements.
E firstWhere (bool test(E element), {E orElse()}) Returns the first element that satisfies the given predicate test.
T fold<T> (T initialValue, T combine(T previousValue, E element)) Reduces a collection to a single value by iteratively combining each * element of the collection with an existing value
Iterable<E> followedBy () Returns the lazy concatentation of this iterable and other.
Set<E> intersection (Set<Object> other) Returns a new set which is the intersection between this set and other.
String join ([String separator = ""]) Converts each element to a String and concatenates the strings.
lastWhere (bool test(E element), {E orElse()}) Returns the last element that satisfies the given predicate test.
E lookup (Object object) If an object equal to object is in the set, return it.
Iterable<T> map<T> (T f(E e)) Returns a new lazy Iterable with elements that are created by * calling `f` on each element of this `Iterable` in iteration order.
void forEach (void f(E element)) Executes a function on each element of the set.
external dynamic noSuchMethod (Invocation invocation) Invoked when a non-existent method or property is accessed..
E reduce (E combine(E value, E element)) Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.
remove (Object value) Removes value from the set. Returns true if value was in the set. Returns false otherwise. The method has no effect if value value was not in the set.
removeAll (Iterable<Object> elements) Removes each element of elements from this set.
void removeWhere (bool test(E element)) Removes all elements of this set that satisfy test.
void retainAll (Iterable<Object> elements) Removes all elements of this set that are not elements in elements.
void retainWhere (bool test(E element)) Removes all elements of this set that fail to satisfy test.
E singleWhere (bool test(E element), {E orElse()}) Returns the single element that satisfies test.
Iterable<E> skip (int count) Returns an Iterable that provides all but the first count elements.
Iterable<E> skipWhile (bool test(E value)) Returns an `Iterable` that skips leading elements while test is satisfied.
Iterable<E> takeWhile (bool test(E value)) Returns a lazy iterable of the leading elements satisfying test.
List<E> toList ({bool growable: true}) Creates a List containing the elements of this Iterable.
Set<E> toSet () Creates a Set with the same elements and behavior as this `Set`.
String toString () Returns a string representation of (some of) the elements of `this`.
union (Set<E> other) Returns a new set which contains all the elements of this set and other.
Iterable<E> where bool test(E element) Returns a new lazy Iterable with all elements that satisfy the predicate test.
Iterable<T> whereType () Returns a new lazy Iterable with all elements that have type T.

Properties

Property Type Description
first E Returns the first element.
last E Returns the last element.
single E Check if the Set only has one element and returns the element. Otherwise it throws error.
length Iterable The number of elements in the set.
isEmpty bool Returns `true` if there are no elements in this collection.
isNotEmpty bool Returns true if there is at least one element in this collection.
hashCode int The hash code for this object.