Dart set explanation with examples

Introduction :

A set is used to store a collection of objects where each object can exist only once in that set. Set is defined in the dart:core library and a couple of other classes that implement set.

Constructors :

Following are the constructors of the set :

  • Set() : Creates one empty set

  • Set.from(Iterable i): Creates one set containing all i.

  • Set.of(Iterable i): Creates one set from i. It creates one LinkedHashSet.

  • Set.identity(): Creates one empty identity set.

Example to create a set :

main(List<String> args) {
  var list = [1,2,3,4,5,5,4,3,2,1];

  var set1 = Set.from(list);
  var set2 = Set.of(list);

  var set3 = new Set();

  for(var item in list){
    set3.add(item);
  }

  print(set1);
  print(set2);
  print(set3);
}

In this example, we have tried three different ways to create one set. All of them will print the same :

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}

Dart example create set

Other set implementers :

LinkedHashSet is the default set implementation. Iteration of set elements also depends on the implementation type. Let me show you a couple of set implementers and how they work:

1. LinkedHashSet :

This is a hash table based set implementation. The iteration is first to last insertion order and it keeps tracks of the order of the elements inserted. It also allows null as an element.

2. HashSet :

This is also a hash table based set implementation but unordered i.e. the iteration order of the elements is not specified. The iteration order depends on the hashcode of the elements. As long as you are not modifying the set, it will always produce the same result for multiple iterations.

3. SetMixin :

Mixin implementation of Set. It provides a base implementation of a Set that depends on add, contains, lookup, remove, iterator, _length, _and toSet. toSet can create a modifiable or unmodifiable set. For an unmodifiable set, you need to implement retainAll, union, _intersection, _and difference.

4. CssClassSet :

This is used to store the CSS class names for an element.

Example of LinkedHashSet and HashSet :

import 'dart:collection';

main(List<String> args) {
  var list = [1, 3, 2, 5, 4, 5, 3, 4, 1, 2];

  Set hashSet = new HashSet();
  Set linkedHashSet = new LinkedHashSet();
  for (var item in list) {
    hashSet.add(item);
    linkedHashSet.add(item);
  }

  print("Printing hashSet : ");
  hashSet.forEach((f) => print(f));

  print("Printing LinkedHashSet : ");
  linkedHashSet.forEach((f) => print(f));
}

It will print :

Printing hashSet : 
1
2
3
4
5
Printing LinkedHashSet : 
1
3
2
5
4

dart example iterate set