Set in Dart Programming


A set is a collection of objects in which each object can occur exactly once. It implies that all the objects in the element type, are either in the set or not in the set.

A set is an important data structure and is very helpful in cases where we need exactly one occurrence of each object.

There are multiple ways in dart with which we can create a Set, but the default way of making use of the Set() constructor is the most common one.

Example

Consider the example shown below −

 Live Demo

void main() {
   var fruits = new Set();
   print(fruits);
}

In the above example, we created a set named fruits which is empty right now, and later we printed the set.

Output

{}

It should be noted that when we create a set using the default way, we are creating a LinkedHashSet in which the difference between two objects is indistinguishable if they are equal when we compare them with the == operator.

We can add objects into a HashSet using the add() method.

Example

Consider the example shown below −

 Live Demo

void main() {
   var fruits = new Set();
   fruits.add("apple");
   fruits.add("mango");
   fruits.add("banana");
   print(fruits);
}

Output

{apple, mango, banana}

We added different fruits in the above example, and as we can see that these fruits were added to the set without any issue. But what if we try to insert an object that is already present in the set.

Example

Consider the example shown below −

 Live Demo

void main() {
   var fruits = new Set();
   fruits.add("apple");
   fruits.add("mango");
   fruits.add("banana");
   var t = fruits.add("apple");
   print(t);
   print(fruits);
   var z = fruits.add("litchi");
   print(z);
   print(fruits);
}

If we already have the object present in the set and still try to insert the same again, then nothing will happen the expression will result in false output.

Output

false
{apple, mango, banana}
true
{apple, mango, banana, litchi}

It is also possible to check whether the set contains a specific object that we are looking for.

Example

Consider the example shown below −

 Live Demo

void main() {
   var fruits = new Set();
   fruits.add("apple");
   fruits.add("mango");
   fruits.add("banana");
   print("has apple? ${fruits.contains("apple")}");
   print("has kiwi? ${fruits.contains("kiwi")}");
}

Output

has apple? true
has kiwi? false

Updated on: 24-May-2021

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements