Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is the set.first method in Dart?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The set.first function in Dart is used to get the reference of the first element in the set.

The image below shows the visual representation of the set.first function.

Visual representation of the set.first function

In Dart, a set is a particular instance of a list in which all of the inputs are unique.

dart:core is required in order to use this function.


If there are duplicates, then the set will only keep the first instance. For instance, {'Tom','Alsvin','Eddie','Tom'} will result in {'Tom','Alsvin','Eddie'}.

Syntax

element set_name.first
// where the set_name is the name of the set.

Parameter

This function does not require a parameter.

Return value

The set.first function returns the reference to the set’s first element.

  • set.first does not remove that element from the set.

  • If the set is empty, then the function throws an error.

Code

The code below shows how to use the set.first function in Dart.

import 'dart:convert';
import 'dart:core';
void main() {
Set<String> set_1 = {'Tom','Alsvin','Eddie'};
//set containing unique value
print("set_1 elements: ${set_1}");
print("set_1 first element: ${set_1.first}");
Set<String> set_2 = {'Tom','Alsvin','Eddie','Tom'};
//set containing non-unique value
print("set_2 elements: ${set_2}");
print("set_2 first element: ${set_2.first}");
}

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring