In the previous episode, you were introduced to the set. You saw that sets have no order and remove duplicates. But I didn’t go into the real power behind behind sets. And that’s comparing sets to other other sets.
The best way to understand the functionality of sets is by way of a Venn diagram. Let’s take to two sets.
One set is for a group iOS developers. Another set contains android developers. Remember, each set holds unique values. Now we have a pool of developers. Some work as an iOS developer. Some work as android developers. But others actually do both.
If we wanted to know which developers worked in both iOS and Android, we’d use an intersection operation.
Let’s say we had a third set of Flutter developers. We could use a union operation to add the flutter developers to the multi-platform developers.
Finally, if we wanted to remove items - for instance, if we wanted to get rid of Flutter developers from the multi-platform set, you use the difference operation. Let’s play around with sets.
To get started, open up a new DartPad instance. Let’s create a new set, that contains car manufacturers who are creating electric cars.
var electricCars = { 'Tesla', 'Ford', 'BMW', 'Rivian' };
Now lets make a list of car manufacturers who make gas cars.
var gasCars = { 'Ford', 'Ram', 'BMW'};
Okay, now let’s perform a simple operation. Let’s get a complete list of cars that make both gas and electric cars. For this we, use the union operator.
var allCars = gasCars.union(electricCars);
print(allCars);
Run the program. Notice we get all the car companies back with the duplicates removed. Now lets see all the companies that just make gas cars. For this we use the difference method.
var justGasCars = gasCars.difference(electricCars);
print(justGasCars);
Now run the program. You’ll see that Ram is the only company that just makes gas cars whereas all the others. Now lets see who makes both electric and gas cars.
var makesGasAndElectricCars = gasCars.intersection(electricCars);
print(makesGasAndElectricCars);
This time we see that Ford and BMW makes both. So as you can see, sets are aren’t just lists that remove duplicates but provide useful grouping operations.