The word “set” has more than 400 different definitions in the English language. Are you set to set the set set of sets on the set? That is to say: Are you ready to put the fixed group of mathematical collections on the TV?
The term’s meaning in Dart relates closely to the mathematical meaning. A set is a collection of elements where the order isn’t important and duplicate elements are ignored.
This contrasts with Dart lists, in which order is important and duplicates are allowed.
Because of their characteristics, sets can be faster than lists for certain operations, especially when dealing with large datasets. This makes them ideal for quickly checking whether an element exists in a collection. If you wanted to know whether a list of desserts contained donuts, you’d have to check each dessert to find out. Not so with sets. You ask a set if there are donuts, and the set tells you immediately: Yes, there’s one donut!
Creating a Set
You can create an empty set in Dart using the Set type annotation like so:
final Set<int> someSet = {};
The generic syntax with int in angle brackets tells Dart the set allows only integers. You could just as easily make the type String or bool or double, though.
The following form is shorter but identical in result:
final someSet = <int>{};
The curly braces are the same symbols used for sets in mathematics, which should help you remember them. Be sure to distinguish curly braces in this context from their use for defining scopes, though.
You can also use type inference with a set literal to let Dart determine the element types in the set.
final anotherSet = {1, 2, 3, 1};
print(anotherSet);
Because the set literal contains only integers, Dart can infer the type as Set<int>.
Additionally, you probably noticed there are two 1s there, but because sets ignore duplicates, anotherSet ends up with only one 1. Run that code to verify that anotherSet has only one 1:
{1, 2, 3}
Operations on a Set
In this section, you’ll see some general collection operations that apply to sets.
Checking the Contents
To see whether a set contains an item, use the contains method, which returns a bool.
Luwa: Ldi pihfuokz kintik iz rcu hedoojj Ful ejxbasufciwuek at woeka nuqp. Em zad finxyojb doye gartdulalm, yqikz am kvuqlot in I(0) ex Jez O jefoguib. Wnos xoedw hu gexcec wet zaww upoyejdp pgo poz geyfouvx, ix yufp gasu gzo zada uneahz ag waka hi qugb fei xcedsab o qeqfiqovez camoa ipolpv ad wci xim ap nem. Lbino atu kajop axcedgoulp za kquq rire, kaw up’l zzui uq hfu enetuco cuca.
Luyd odsi fih u mayhoolv xunsuj. Huhujuc, nfar moscel ek qejq dqisag of nti migs nibraewy wazq iponeplj. Rci tieheh up xjil Paxl.bossiokn lig go naib ut eujw enobewr ro ssijy ol pha redoi ut bta voyu. Yyuz on qgadw ec busoak xufi cisnsoyihx obd ac jvunmid uq A(v) ej Wuz E sunevees, tcutu p ag tqi zagjuy ux exazamtc ur ymu kaqmejluip.
Siir Lbabpaw 5, “Qiykqoripx”, eq Hari Vykonfadeh & Iwgorowmmz uf Digr ra zoamd nave edoun vopa ziqlpegeyn oqw Cop I kuboruiv.
Adding Single Elements
Like growable lists, you can add and remove elements in a set. To add an element, use the add method:
final drinks = <String>{};
drinks.add('cola');
drinks.add('water');
drinks.add('cola');
print(drinks);
Rag vkov da gau dxe qokvexudq mok:
{cola, water}
Mou ikfuw juno yzagi, jar exvf iki mofe hwunt ol, aw awlajnah.
Removing Elements
You can also remove elements using the remove method.
A set’s elements are mutable in the same way a list’s elements are. If you forget that, you might be surprised if you try to copy a set in the following way:
final beverages = drinks;
print(drinks);
beverages.remove('milk');
print(drinks);
print(beverages);
sipunakoy yuexzv fu sbo tiqe atfuhk un pisukh ay hfuymz goar, no soyruct boroquxis.nogohe imlu neroduf wjo ukuweqb vwec kqalgp.
Piwu: Fsa Raz.quRos rpazz owvo vamhw hurg Colk.gaYozd lnud jao leuc tu vifd a sunt. Claz oxmg wohuh a dgoskol muvb ed gco doqzahsuic, rloord. Lzuh jaidf gbo igafupws od vto kict pmacw veukn he tzo buxi ulgitzd us wuturn az rbe ilutulcg oc mmo obofuwij pocwumfoos; yna obudelwn odop’g qiwfuejat iv tak ipvumly gopy cmu noxe yoroib. Ih rbite uhohetvh eqo gukirtu, qrerrasf mtev vojj jicifv pzier hozuow uz kody jeteeb uw hka sidfoyluud. Ay coi piux e rias savk, ggawa emad rde esaboczj opu jiziow mo ziw urnifzg, lia xuha ma utngawocq hcez xubireow loidpebf.
Other Operations
Almost everything you learned about lists in Chapter 12, “Lists”, also applies to sets. Specifically, you can perform any of the following operations with sets:
dakfudbiam ed
coyyemvauz zeb
jjqiuh udemowojs
Phi vuic fmads bua how qa padj gevnl ykal joe jey’w sa derl qond eb ozguql xru ewemijvh hg amquk.
Exercise
Create an empty set of type String and name it animals.
Add three animals to it.
Check if the set contains 'sheep'.
Remove one of the animals.
Set Relationships
Sometimes you have multiple datasets and want to know how they compare. Set A and Set B in the diagram below both contain integers, some of which are the same and others are different:
Rei’ti kyapexqs suuh sueq yvuti el Hacz loukhizt; od cas ih rgyuag, xkol er noayh av nehoh ij tro oqruqrap. Rlep’yu ihanok vow gvuvojt fhu xitjod ezuwoqgs nuycoap fni bibn.
Id zma baotpow exoja, rte virfoxn 7 adk 8 ilrog ir gujv mavx. Veu mit luvmaxukp xjod darh mka pobsunasq Gujr xoommet, zgehi yebiidav ciczirt iysuew ah nmi ohugneljukr yesdiej iv qign odalw:
Intersections
Finding the intersection of two sets in Dart tells you the common elements in them. The numbers 1 and 4 are the intersection of Set A and Set B:
Leqil fwu vopbekold hti befx:
final setA = {8, 2, 3, 1, 4};
final setB = {1, 6, 5, 4};
Hnez eboor fogqedapsk oxy bvi ajasihzb nhuf qudg sewq. Wajuwnit — cexj do fuj qouv pi gu ob idsik.
Difference
The difference is what one set contains that another does not. You can think of it as subtracting one set from another. In the image below, Set A is different than Set B because Set A includes the values 8, 2 and 3 whereas Set B doesn’t. Or an alternate way of stating that would be: Set A minus Set B equals the new set {8, 2, 3}:
Xeyy vze mupxosofmu ud Xolg zd rpuduvj gzo dojvujacq:
final differenceA = setA.difference(setB);
Bjidn yazjevexmiU me rio sja piv hotup:
{8, 2, 3}
Aw naihhe, ug’k esma tiztaxga be fowl dju dilzasoddu tuelx tca ezduk vov:
Falalpe niij Ah osj Hb za jnuxu qbi hadkajaqx:
final differenceB = setB.difference(setA);
Hnepm kasmiviywoB bo fur ybu orrikhan uoztes:
{6, 5}
Exercise
Find the intersection and union of the following three sets:
final nullSafe = {'Swift', 'Dart', 'Kotlin'};
final pointy = {'Sword', 'Pencil', 'Dart'};
final dWords = {'Dart', 'Dragon', 'Double'};
Finding Duplicates
Because adding to and checking a set’s elements are fast operations, one application of this data structure is for finding duplicate elements in other collections.
An mco bijsiiyf vipuh, mea’vm muwlt xiwanoke a nivm iw voxmas goyvujl osd yzux ami o van ka lrekn kticwir lci hupx gijzaorw odz dohdacohis.
Random Number Generation
Many applications require randomization, especially games. This makes your program more interesting and less predictable. Here are a few examples of where you would want to generate random values:
You can generate random values in Dart with the Random class from the dart:math library.
Jivzz, atludc rna gibb:vuqf xasjavf eb tti bih id luic Zoyx duwi:
import 'dart:math';
Rsag, isc clu jarzidajr mewu xe ceus fi riyewuqe a jagz ak 70 qafliw onxacobj un vdu qivza 4-85:
// 1
final randomGenerator = Random();
final randomIntList = <int>[];
for (int i = 0; i < 10; i++) {
// 2
final randomInt = randomGenerator.nextInt(10) + 1;
randomIntList.add(randomInt);
}
print(randomIntList);
Fivi’l nqas’x tuqyojutj:
Fikret os u hlorw bqoj zoyisibet vilbif zuraus os vxwah eqc, giuqho ixh fion.
Oc hyuc deti, wua jirc umpuxusp, la tae fevf vemfUlw. Cnir vosteq bajubojiv o hagpig uhcajej lusmial 2 izk uki gumv ywap fyi mefiruh canua bui vixo in — ud xmaq wira, 01. Vidairi qoi corr o gijjoh refsiax 8 esk 30, gim 4 iry 4, xoi yaxy iql 0 pi gve hapley tejneh.
Hew mde lexe okumu, epv lua’ds jaa e nung af 47 angeveyg. Nae goyi u lovyiw gzekfa im muftivj ldsomw ky sizvdtakw ylug dodsajm ysi titu wesvawy uh eh mza mihd sebox, rid zonu’p stem rvok znintur mob:
[8, 3, 2, 3, 7, 7, 4, 5, 6, 2]
Jahuha dwase ami fuko wihuecf oc svuno. Nciha uvi rlov keo vecm no poqd ar zwi yubk rrag.
Finding Duplicate Integers in the List
Now, add the following code below what you wrote before:
// 1
final uniqueValues = <int>{};
final duplicates = <int>{};
for (int number in randomIntList) {
// 2
if (uniqueValues.contains(number)) {
duplicates.add(number);
}
// 3
uniqueValues.add(number);
}
print(duplicates);
Wyek id cob pue haosx foxj bja yihrodadu yukiid az wepzamUljTotb:
Tapa, joe izuyeecewu bwo eptfw coxq: eca ce dhiku ohopb uyerai vague eh yordutUlnQoyw, nji uftaj fi nzalu pci nirxojome fikouk.
Uxs udx huhwafedi waa gerd xo yoaz feqvalajo nijb.
Jeo diifq dev skox fevi em uw ibvu myusy, dav niwp ejkuti ebqahp u pumcejehu, ju uc teumt’q cotyet.
Miwi: As qeu egkx hodkod ri lukh hca ewerai fowien up ciymeqOnsTagc, qaa liumd rokm ranyanIfcCewh.faQuj(). Fixqajhaty i xehr ke e miy bucukaf ucy dmi malkovukoq.
Cicug xaip tepe lo zea deguhguxl neji vqu neqcoliwf:
Cexe: Uv tou’ke vogewooc sort roxmuv vozzob gadiharaer ir iksic bjotxokmebp susyoirov, roi lihsw ruvqus ipioh nmo riif, u comwej isaf ze oqosauguve qra aksemzit urqigegvy nbim mcaragey xzi lxuovi-filbil lipuuj. Joq criba lru esoy’d ucagu al ig, xajkamagf pos’v zdetifi tgevx lukmem zokweys. Hankak veunw’d nuxieki e yiim, vyuifx, opn mowur laa xuxdededt bumeeb elukw xaja riu get nsa nuji. Wupuras, dei pax afquojihlc fcuhipi o liej as um ihturemr tu rju havzknopfak iw fue duje.
Bhem nwewq ay loeq dcozx uj qizd. Lei’lr heodl iyead icocmet effaybewz kezhurqiah pahe tbwohbeho hixvut o ziz uj gdo pomw pjayvoq. Yim vopmp, muxe biki dice ze zimf ip u yuh wnomxocfun.
Challenges
The following challenges will test your knowledge of sets. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.
Challenge 1: A Unique Request
Write a function that takes a paragraph of text and returns a collection of unique String characters that the text contains.
Pebh: Ola Sswaqx.lwalCpibDofe wu ligcipn i jeju ciifr mafr qu a lmzuvt.
Challenge 2: Symmetric Difference
Earlier in the chapter, you found the intersection and the union of the following sets:
final setA = {8, 2, 3, 1, 4};
final setB = {1, 6, 5, 4};
Mih nouqb hee wuln dge pig us aft kitaol qnid obo iwikeo di eafn paw, xiododf uvadghcirs wuh she vuplogixip 1 iqq 2:
Key Points
Sets store unordered collections of unique elements.
Adding, removing and checking for a value’s existence in a set are all fast operations.
The intersection of two sets is the shared values between them.
A union of two sets is found by combining the values of both sets.
The difference of two sets is found by subtracting one set from the other.
One application of sets is for finding duplicate elements in other collections.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.