loading

Dart Sets

An unordered collection of various values of the same type is called a dart set. It is unordered yet has much of the same functionality as an array. Duplicate value storage is not permitted by sets. There must be unique values in the set.

It is crucial in situations where we wish to store different types of data in one variable. We can only have values of the same type after the type of the Set is declared. The elements’ order cannot be maintained by the set.

Dart Initializing Set

There are two ways to declare or initialize an empty set in Dart. The set can be declared using the curly braces {} followed by a type argument, or by using the curly braces {} to declare the variable type Set. The following is the syntax for declaring a set.

Syntax

				
					var setName = <type>{};  
Or   
Set<type> setname = {};   
				
			

The set variable’s name is indicated by the setname, while the set’s data type is indicated by the type.

Note: Keep in mind that the set’s syntax is very similar to that of the map literals. The Dart compiler will produce a Map object rather than a Set if the type annotation is not defined with {} or the variable it is allocated to.

Example

				
					void main(){  
   print("Initializing the Set");  
   var names = <String>{"James","Ricky", "Devansh","Adam"};  
   print(names);  
}  
				
			

Output

				
					Initializing the Set
{James, Ricky, Devansh, Adam}
				
			

Add Element into Set

The add() and addAll() methods in the Dart allow you to add an element to the specified set. The single item is added to the specified set using the add() method. When several elements are added to an existing set using the addAll() method, it can add them one at a time. Below is the syntax.

Syntax

				
					Set_name.add(<value>);  
Or   
Set_name.addAll(val1,val2....valN)  
				
			

Example

				
					void main(){  
   print("Insert element into the Set");  
   var names = {"James","Ricky","Devansh","Adam"};   
   // Declaring empty set  
   var emp = <String>{};  
   emp.add("Jonathan");  
   print(emp);  
     
   // Adding multiple elements  
   emp.addAll(names);  
   print(emp);  
}  
				
			

Output

				
					Insert element into the Set
{Jonathan}
{Jonathan, James, Ricky, Devansh, Adam}
				
			

Explanation

Two sets of names and emp have been announced. Emp is an empty set; the set names were composed of few components. Then, we ran the addAll() method and supplied another set of names as an input. We had added the single element “Jonathan” using the add() method. It expanded the emp set by adding the multiple values.

Access the Set Element

The elementAt() function in Dart allows you to retrieve an item by supplying it its given index location. Starting at zero, the set indexing rises to size – 1, where size is the total number of elements in the set. If we enter a larger index number than its allowed size, an error will be raised. Below is the syntax.

Syntax

				
					Set_name.elementAt(index)  
				
			

Example

				
					void main(){  
   print("Access element from the Set");  
   var names = {"James","Ricky","Devansh","Adam"};  
   print(names);  
     
   var x = names.elementAt(3);  
   print(x);  
}  
				
			

Output

				
					Access element from the Set
{James, Ricky, Devansh, Adam}
Adam
				
			

Explanation

The example above uses fixed names. We used the elementAt() function and supplied the parameter for index position 3. The assessed value was placed in a variable called x, and the outcome was printed after that.

Dart Finding Element in Set

The contains() method in Dart is used to locate an element within a set. It takes one item as an input and outputs the result in Boolean format. It returns true if the supplied element is in the set and false otherwise. Below is the syntax.

Syntax

				
					set_name.contains(value);
				
			

Example

				
					void main()  {  
  
  print("Example - Find Element in the given Set");  
  var names = <String>{"Peter","John","Ricky","Devansh","Finch"};  
  
  if(names.contains("Ricky")){  
     print("Element Found");  
  }  
  
  else {  
    print("Element not found");  
 }  
}  
				
			

Output

				
					Example - Find Element in the given Set
Element Found
				
			

Explanation

In the program above, we invoked the contains() function and gave the value “Ricky” as an argument in order to find the element in the specified set. To determine whether an element is a part of the specified set or not, we employed the conditional statement. When the specified element was found in the set, the condition was satisfied, and the if block statement was printed.

Note – We will learn conditional statement in the next section.

Dart Remove Set Element

To remove an element from the specified set, use the remove() method. The value is passed in as an argument, and its removal from the specified set is required. Below is the syntax.

Syntax

				
					set_names.contains(value)  
				
			

Example

				
					void main()  {  
  
    print("Example - Remove Element in the given Set");  
    var names = <String>{"Peter", "John", "Ricky", "Devansh", "Finch"};  
    print("Before remove : ${names}");  
  
     names.remove("Peter");  
     print("After remove  :  ${names}");  
}  
				
			

Output

				
					Example - Remove Element in the given Set
Before remove : {Peter, John, Ricky, Devansh, Finch}
After remove  :  {John, Ricky, Devansh, Finch}
				
			

Explanation

Using the remove() method, we eliminated “Peter” from the provided set in the application above. The updated set object was given back.

Dart Iterating Over a Set Element

The forEach method in Dart can be used to iterate the set element as follows:

Example

				
					void main()  {  
    print("Example - Remove Element in the given Set");  
    var names = <String>{"Peter","John","Ricky","Devansh","Finch"};  
  
    names.forEach((value) {  
        print('Value:  $value');  
     });  
} 
				
			

Output

				
					Example - Remove Element in the given Set
Value:  Peter
Value:  John
Value:  Ricky
Value:  Devansh
Value:  Finch
				
			

Dart Remove All Set Element

By using the clear() techniques, we can eliminate the entire set element. It returns an empty set after deleting or removing every element from the supplied set. The following is the syntax:

Syntax

				
					set_name.clear(); 
				
			

Example

				
					void main()  {  
    print("Example - Remove All Element to the given Set");  
    var names = <String>{"Peter","John","Ricky","Devansh","Finch"};  
      
    names.clear();  
    print(names);  
  
}  
				
			

Output

				
					Example - Remove All Element to the given Set
{Peter, John, Ricky, Devansh, Finch}
{}
				
			

TypeCast Set to List

The toList() method can be used to transform a Set object into a List object. The following is the syntax.

Note: The types of Lists and Sets must match exactly.

Syntax

				
					List<type> <list_name> = <set_name>. toList();  
				
			

Dart Set Operations

The Dart Set offers the ability to carry out the subsequent set actions. Below is a list of these operations.

Union: The value of the two supplied sets, a and b, is combined by the union.

Intersection: All components that are shared by both sets are returned when set a and set b intersect.

Subtraction: When two sets, a and b, are subtracted, the result is a-b, or the element of set b that is absent from set a.

Example

				
					void main()  {  
  
    var x = <int>{10,11,12,13,14,15};  
    var y = <int>{12,18,29,43};  
    var z = <int>{2,5,10,11,32};  
    print("Example - Set Operations");  
      
    print("x union y is -");  
    print(x.union(y));  
  
    print("x intersection y is - ");  
    print(x.intersection(y));  
      
    print("y difference z is - ");  
     print(y.difference(z));   
      
}  
				
			

Output

				
					Example - Set Operations
x union y is -
{10, 11, 12, 13, 14, 15, 18, 29, 43}
x intersection y is -
{12}
y difference z is -
{12, 18, 29, 43} 
				
			

Dart Set Properties

The following are the few attributes of the Dart set.

PropertiesExplanations
firstIt is used to get the first element in the given set.
isEmptyIf the set does not contain any element, it returns true.
isNotEmptyIf the set contains at least one element, it returns true
lengthIt returns the length of the given set.
lastIt is used to get the last element in the given set.
hashcodeIt is used to get the hash code for the corresponding object.
SingleIt is used to check whether a set contains only one element.
Share this Doc

Dart Sets

Or copy link

Explore Topic