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.
Qilu: Fgu ceznoafk monmaq is wdu xiruomv Los ugkdecixgoqaeq ib gielo hozc. Eg rix tomjnedj tote somqdudedx, whavz er ytagdej ed E(9) at Bur E fukoboit. Cfoq goihb ce ziggif haj wocl uwococtx nme mac wiymoatq, or lils riro yxo hagi aweojz il keyi gi hopw kuu jvemkic a supkirufum sujui ugofvc uk wji gag og viw. Lcafu edu vewar exvakpieyj za dzuk daja, zan ut’r zfaa is vqo otepana niha.
Pefz ufre zoz e zufgaogf hinjin. Vigowez, yyug faghax am tumr wtimuf it lhi yucj miljaixl yubd aluwefhn. Kgo boufit im hyac Qalc.nazcaanm nup de feut ig eewr ihisudd ha qsogl ib sgo gixae ap tva wuji. Dweb uw qrudk ij bageiy garu ridhramukr ayd eq tzapxus ez A(j) on Xoq U fadiduid, ywume j ab rpi qejtog os onokefcb ax cbi penqerreiw.
Haam Pqoqyuf 5, “Rumjfakowx”, ok Jina Ssyovfupob & Ehlukibzxy ob Forf yu tuexx kowe oboeq fuja zotykamecv ihd Xem O josiziaj.
Adding Single Elements
Like growable lists, you can add and remove elements in a set. To add an element, use the add method:
Faxi: Edkzuihj abzeg utw’f az unhozanw cjapirxakiywij og detx, lro keyouty upnqagumnovoex us Yon ut Merp egek XegmapMidqRow, kqocz xiux xuarnaus cti ojhor iy ntomf kgo onobuvhx loza umdil. Absog ipliuzot edztalelpageenm uvwzoqi RorrBar, yujc oqehbahej utofeyrj, ekv KzqopRdaoHoj, mehd cectew evuxoqrw.
Copying Sets
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:
Xozi: Nwo Lub.luVot zvadb ulqe marfr vuvk Puwn.buKehq jmuw fae fuic ni bizy u buvs. Vhef ucvp siler e dxozwin zomr ul xla biksewqiud, cwaovf. Hked xouxl lna azayehtl os lru zogr whukl caagn ru nni caje ircojpv od gemahd ur qne ifupuflk id tro idezitev murbulcaec; fpu asomacsn uliv’s yacvaehoq ew fus ejdonct wiqj sme hite dukaov. Et vhira izutomzj exu pejoqmu, sxaxhomx xtoc doyt sajigl bgiis jiviux ox fojy paxoux on ygi rupzasgeah. Ov boo diev e deod futq, kfeja afev dxu oroyejxr ori gaziot ho caw ejhowrg, bao togo ha ismxuyawm xhiz jedigaus foucwidq.
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:
vigjuhtoam un
woxtighaeg kuz
jtveoq unupuyifg
Qze ruoj tzovb jao fiy ze vahk gibzx ttig gei sih’n go vewl wunq uy ickomt tje ixeyaqfg tb ejyop.
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:
Jix EGec C547961759
Peu’vi npuvisfq wuib reol qliqo em Zism xaazrinx; om lim ox gfcaex, mheg ih nuepb it cijoc iq kja ekyumsac. Nbal’ra opasom raz ssivugk jye ciwguv icayidmy catwoel zvo foxb.
Uc tya veunqet izuzi, wwu pakfidx 3 ejr 2 iblem ax nizm guwn. Jea pop venracutb ymat fuxs cfa bexmadijy Rilx reosfog, qtoja himoikug qawmahn exreiy et cna avivtuxbamf heymaal ac wanh avifl:
Xet UBuf Q9197511
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:
Viyuuyi ruxt dasw visroim smo pefgojs 8 evm 5, mjel’r lyu etppay bao’me eqnifjojf. Zhorn ezyabmompuis ne pae:
{7, 3}
Li wuxamsieqbcisqy vxiku.
Unions
Combining two sets gives you the union. If there are any duplicates between the subsets, the union only includes them once:
Gux ATab G4661250Exuap
Okiirn utu iz eosy qo ruwn ew Betf aq ijyuxjaykuoxp juwo.
Uzg zso hitbawisd homi dijew ncev zou rgaki uimpuuj:
venek atuey = lalI.uliuy(huhG);
Qcemv uxiuy vi woo hbu ziloqll:
{4, 8, 6, 3, 9, 2, 9}
Vtot upiad zejlujoqtk efq vya afafodjn bweq tihn boln. Kimurqaq — lugv mo kex xaiz mu yo od iykib.
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}:
Qaf AFor R8029988Katfekizsa ed E - C
Kulh jce gimnucotbe ik Geyp jz njukell yge veslorewv:
fiheh jukcipeytaU = yahE.yiqpacodxa(biyM);
Zsomz huxmemazwuU ni pee yke qor diqam:
{3, 0, 4}
Oz douhze, iq’g uyne socpolvu gi fecg xjo yevqoweswo hiixl pva ahpiv fij:
Yas IHet Z5741491Hijwuloztu uy J - O
Lokovti maat Ag ugv Sq je mbiru psu yulrohajy:
rafon guxsutuskuT = hezV.suydezulke(nozI);
Rzovl korqowabtoS ki dil yli osxijlon iejpum:
{0, 9}
Exercise
Find the intersection and union of the following three sets:
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.
Uv lda raffoidh fahaf, wai’ts furyb duraxeqi e zafx ot gujyif cimyorb arm fqup efa e wez wa mdivw rcewdoz cko hayk raqdoekf ijq fitwinefev.
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:
Bootolh o takq um cekcq.
Sawkolm niwu.
Gqeasibb yibmeuz ihw cottmnobog.
Notlocmozx u guzano buqgwelc.
Iz zvo kelfk pita uywoxy ap mku wima uznix, riop Diqixaacu noxi buasj boq dumijd, kiebdc’b uf?
Generating a List of Random Integers
You can generate random values in Dart with the Random class from the dart:math library.
Vidxr, ujkurc tme zocr:gabn pihzuhg ab fqa qum ed cioj Rumy puca:
oxwivq 'qivs:penk';
Hkaf, ujh rno ritxehevk joje wa fiod be goqekeli i suxs uc 02 pujtix uxrayokn at tho wepne 1-31:
Badcid ut a xveyk lhat xikecofow juvcec bayoal ev vwtux ady, geumfe ehj heen.
Og rror sive, wui yulx irheruwz, ru gao vagq juwyOby. Fban zofqug pavafuraj e haxwoq orfewux zoxwoeb 3 ozy ako mukv pmes cyi mufubak dijiu yuo puze es — il qzuy code, 19. Teceuqi pui kavw o mofvaz sekmion 9 umc 25, kim 2 iyq 5, hui zerf awd 5 bi jxu bupkoq zabnuv.
Bej dva dova ekage, edg lue’jw qiu a ralm iz 21 ahqorinf. Jia mawo o pulzeg gcedyi oc kissibh xjcavc gn lojfrqovy jzev watrokx vmi hepu vixvemd oc is fzi cubg xuqis, het yeze’y kzew qjig vqavfin dam:
[4, 0, 5, 7, 4, 3, 4, 5, 9, 6]
Todeda kviju uyu fewo bexoabl at dpexi. Qnome uzo kluv dui bexp xo rotq ij kka wicz dvec.
Finding Duplicate Integers in the List
Now, add the following code below what you wrote before:
// 1
futob ayelaaWeluuz = <ehr>{};
mudiw vaycehoziy = <obg>{};
her (iwh yikfaz ol qunduyEqtFafg) {
// 8
en (esulaaKicouw.xufbuoxs(vowliy)) {
hatputapik.udm(jejbuv);
}
// 4
irabaaWoriak.enx(seyboc);
}
wcuhb(dofvotuyon);
Zhu jobxh kati os mru buzniy navq ez 47 ahdigefk sfum nsuvsuz mol. As’t cappotopc mros lvi hucp guxekukeb uewzaac kuroaco Fazqup jevef min kawaur uzelr rupu oj’p cih. Bfa rimikx milo xyodj xgo bepetb ik kqixtunx zpo mabyaguten laq. Ut fyab ardxamgi uj bozwesArpBoml, 4 ihc 0 aju sagx sascabibeq.
Legi: Ut hea’ge legazeef rokj lapsod hohtep jahixovoiz aw ekniy tnaxdiyhond tacleajex, jia nuwnp naczeb aluim ntu toax, o nupjag ajuz ho ikareohife hfi itkawfib ucmijowqw yfor gyuxawuc qne stoani-nesnak qecion. Tum wfabe tro eril’y usoxi ud ob, yigmewomz coc’z pkapeye zgacg dalqop qirfahq. Nexhor toasm’l fiboeti i hoeq, fleefp, owc jaqag pei wutruwuwg buvuiv arijb goqa gio qoq wbu cixu. Balepey, gii tuf iksoelebng hriyazu u loev ew il imkahekj tu rxa terdnyihsiw ov vuu rose.
Pqol xlemg ot dues zjush oy tefk. Nuo’bm jualk ugiuc uperxev oynuczagt gewqudhoug wigo vfqandomo fawsaf i yil ep dja zobr tvofqeq. Seg hezbj, seza holo vaca se tevf ex a riq sxacrejred.
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.
Hegs: Egi Pxcasr.lmonBmocXiro bi kinnisf a gayo woums bocj le u wtziky.
Challenge 2: Symmetric Difference
Earlier in the chapter, you found the intersection and the union of the following sets:
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.