1# @ohos.util.TreeSet (Nonlinear Container TreeSet)
2
3**TreeSet** is implemented based on **[TreeMap](js-apis-treemap.md)**. In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique.
4
5**[HashSet](js-apis-hashset.md)** stores data in a random order, whereas **TreeSet** stores data in sorted order. Both of them allow only unique elements. However, null values are allowed in **HashSet**, but not in **TreeSet**, because null values may affect the order of elements in the container.
6
7Recommended use case: Use **TreeSet** when you need to store data in sorted order.
8
9This topic uses the following to identify the use of generics:
10
11- T: Type
12
13> **NOTE**
14>
15> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
16
17
18## Modules to Import
19
20```ts
21import { TreeSet } from '@kit.ArkTS';
22```
23
24## TreeSet
25
26### Attributes
27
28**Atomic service API**: This API can be used in atomic services since API version 12.
29
30**System capability**: SystemCapability.Utils.Lang
31
32| Name| Type| Readable| Writable| Description|
33| -------- | -------- | -------- | -------- | -------- |
34| length | number | Yes| No| Number of elements in a tree set (called container later).|
35
36
37### constructor
38
39constructor(comparator?: (firstValue: T, secondValue: T) => boolean)
40
41A constructor used to create a **TreeSet** instance. It supports sorting elements in ascending or descending order by using comparators.
42
43**Atomic service API**: This API can be used in atomic services since API version 12.
44
45**System capability**: SystemCapability.Utils.Lang
46
47**Parameters**
48
49| Name| Type| Mandatory| Description|
50| -------- | -------- | -------- | -------- |
51| comparator | function | No| Custom comparator, which can be used to sort elements based on the comparison relationship. The default value is **hole** (a blank placeholder), indicating that no comparator is provided.|
52
53**Error codes**
54
55For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
56
57| ID| Error Message|
58| -------- | -------- |
59| 401      | Parameter error. Possible causes: 1.Incorrect parameter types; 2.Parameter verification failed. |
60| 10200012 | The TreeSet's constructor cannot be directly invoked. |
61
62**Example**
63
64```ts
65// Default constructor.
66let treeSet : TreeSet<string | number | boolean | Object> = new TreeSet();
67```
68
69```ts
70// Use the comparator firstValue < secondValue if the elements are expected to be sorted in ascending order. Use firstValue > secondValue if the elements are expected to be sorted in descending order.
71let treeSet : TreeSet<string> = new TreeSet<string>((firstValue: string, secondValue: string) : boolean => {return firstValue < secondValue});
72treeSet.add("a");
73treeSet.add("c");
74treeSet.add("d");
75treeSet.add("b");
76let numbers = Array.from(treeSet.values())
77for (let item of numbers) {
78  console.log("TreeSet:" + item);
79}
80```
81
82```ts
83// When a custom type is inserted, a comparator must be provided.
84class TestEntry{
85  public id: number = 0;
86}
87let ts1: TreeSet<TestEntry> = new TreeSet<TestEntry>((t1: TestEntry, t2: TestEntry): boolean => {return t1.id > t2.id;});
88let entry1: TestEntry = {
89  id: 0
90};
91let entry2: TestEntry = {
92  id: 1
93}
94ts1.add(entry1);
95ts1.add(entry2);
96console.log("treeSet: ", ts1.length);
97```
98
99
100### isEmpty
101
102isEmpty(): boolean
103
104Checks whether this container is empty (contains no element).
105
106**Atomic service API**: This API can be used in atomic services since API version 12.
107
108**System capability**: SystemCapability.Utils.Lang
109
110**Return value**
111
112| Type| Description|
113| -------- | -------- |
114| boolean | Returns **true** if the container is empty; returns **false** otherwise.|
115
116**Error codes**
117
118For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
119
120| ID| Error Message|
121| -------- | -------- |
122| 10200011 | The isEmpty method cannot be bound. |
123
124**Example**
125
126```ts
127const treeSet : TreeSet<string | number | boolean | Object>  = new TreeSet();
128let result = treeSet.isEmpty();
129```
130
131
132### has
133
134has(value: T): boolean
135
136Checks whether this container has the specified value.
137
138**Atomic service API**: This API can be used in atomic services since API version 12.
139
140**System capability**: SystemCapability.Utils.Lang
141
142**Parameters**
143
144| Name| Type| Mandatory| Description|
145| -------- | -------- | -------- | -------- |
146| value | T | Yes| Target value.|
147
148**Return value**
149
150| Type| Description|
151| -------- | -------- |
152| boolean | Returns **true** if the specified value is contained; returns **false** otherwise.|
153
154**Error codes**
155
156For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
157
158| ID| Error Message|
159| -------- | -------- |
160| 10200011 | The has method cannot be bound. |
161
162**Example**
163
164```ts
165let treeSet : TreeSet<number> = new TreeSet();
166treeSet.add(123);
167let result = treeSet.has(123);
168```
169
170### getFirstValue
171
172getFirstValue(): T
173
174Obtains the value of the first element in this container.
175
176**Atomic service API**: This API can be used in atomic services since API version 12.
177
178**System capability**: SystemCapability.Utils.Lang
179
180**Return value**
181
182| Type| Description|
183| -------- | -------- |
184| T | Value obtained. If nothing is obtained, **undefined** is returned.|
185
186**Error codes**
187
188For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
189
190| ID| Error Message|
191| -------- | -------- |
192| 10200011 | The getFirstValue method cannot be bound. |
193
194**Example**
195
196```ts
197let treeSet : TreeSet<string> = new TreeSet();
198treeSet.add("squirrel");
199treeSet.add("sparrow");
200let result = treeSet.getFirstValue();
201```
202
203
204### getLastValue
205
206getLastValue(): T
207
208Obtains the value of the last element in this container.
209
210**Atomic service API**: This API can be used in atomic services since API version 12.
211
212**System capability**: SystemCapability.Utils.Lang
213
214**Return value**
215
216| Type| Description|
217| -------- | -------- |
218| T | Value obtained. If nothing is obtained, **undefined** is returned.|
219
220**Error codes**
221
222For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
223
224| ID| Error Message|
225| -------- | -------- |
226| 10200011 | The getLastValue method cannot be bound. |
227
228**Example**
229
230```ts
231let treeSet : TreeSet<string> = new TreeSet();
232treeSet.add("squirrel");
233treeSet.add("sparrow");
234let result = treeSet.getLastValue();
235```
236
237
238### add
239
240add(value: T): boolean
241
242Adds an element to this container.
243
244**Atomic service API**: This API can be used in atomic services since API version 12.
245
246**System capability**: SystemCapability.Utils.Lang
247
248**Parameters**
249
250| Name| Type| Mandatory| Description|
251| -------- | -------- | -------- | -------- |
252| value | T | Yes| Target element.|
253
254**Return value**
255
256| Type| Description|
257| -------- | -------- |
258| boolean | Returns **true** if the element is added successfully; returns **false** otherwise.|
259
260**Error codes**
261
262For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
263
264| ID| Error Message|
265| -------- | -------- |
266| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
267| 10200011 | The add method cannot be bound. |
268
269**Example**
270
271```ts
272let treeSet : TreeSet<string> = new TreeSet();
273let result = treeSet.add("squirrel");
274```
275
276
277### remove
278
279remove(value: T): boolean
280
281Removes the element with the specified key from this container.
282
283**Atomic service API**: This API can be used in atomic services since API version 12.
284
285**System capability**: SystemCapability.Utils.Lang
286
287**Parameters**
288
289| Name| Type| Mandatory| Description|
290| -------- | -------- | -------- | -------- |
291| value | T | Yes| Key of the target element.|
292
293**Return value**
294
295| Type| Description|
296| -------- | -------- |
297| boolean | Returns **true** if the element is removed successfully; returns **false** otherwise.|
298
299**Error codes**
300
301For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
302
303| ID| Error Message|
304| -------- | -------- |
305| 10200011 | The remove method cannot be bound. |
306
307**Example**
308
309```ts
310let treeSet : TreeSet<string> = new TreeSet();
311treeSet.add("squirrel");
312treeSet.add("sparrow");
313let result = treeSet.remove("sparrow");
314```
315
316
317### getLowerValue
318
319getLowerValue(key: T): T
320
321Obtains the value that is placed in front of the input key in this container.
322
323**Atomic service API**: This API can be used in atomic services since API version 12.
324
325**System capability**: SystemCapability.Utils.Lang
326
327**Parameters**
328
329| Name| Type| Mandatory| Description|
330| -------- | -------- | -------- | -------- |
331| key | T | Yes| Input key.|
332
333**Return value**
334
335| Type| Description|
336| -------- | -------- |
337| T | Value obtained. If nothing is obtained, **undefined** is returned.|
338
339**Error codes**
340
341For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
342
343| ID| Error Message|
344| -------- | -------- |
345| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
346| 10200011 | The getLowerValue method cannot be bound. |
347
348**Example**
349
350```ts
351let treeSet : TreeSet<string> = new TreeSet();
352treeSet.add("squirrel");
353treeSet.add("sparrow");
354treeSet.add("gander");
355let result = treeSet.getLowerValue("sparrow");
356```
357
358
359### getHigherValue
360
361getHigherValue(key: T): T
362
363Obtains the value that is placed next to the input key in this container.
364
365**Atomic service API**: This API can be used in atomic services since API version 12.
366
367**System capability**: SystemCapability.Utils.Lang
368
369**Parameters**
370
371| Name| Type| Mandatory| Description|
372| -------- | -------- | -------- | -------- |
373| key | T | Yes| Input key.|
374
375**Return value**
376
377| Type| Description|
378| -------- | -------- |
379| T | Value obtained. If nothing is obtained, **undefined** is returned.|
380
381**Error codes**
382
383For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
384
385| ID| Error Message|
386| -------- | -------- |
387| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
388| 10200011 | The getHigherValue method cannot be bound. |
389
390**Example**
391
392```ts
393let treeSet : TreeSet<string> = new TreeSet();
394treeSet.add("squirrel");
395treeSet.add("sparrow");
396treeSet.add("gander");
397let result = treeSet.getHigherValue("sparrow");
398```
399
400
401### popFirst
402
403popFirst(): T
404
405Removes the first element in this container.
406
407**Atomic service API**: This API can be used in atomic services since API version 12.
408
409**System capability**: SystemCapability.Utils.Lang
410
411**Return value**
412
413| Type| Description|
414| -------- | -------- |
415| T | Element removed. If nothing is obtained, **undefined** is returned.|
416
417**Error codes**
418
419For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
420
421| ID| Error Message|
422| -------- | -------- |
423| 10200011 | The popFirst method cannot be bound. |
424
425**Example**
426
427```ts
428let treeSet : TreeSet<string> = new TreeSet();
429treeSet.add("squirrel");
430treeSet.add("sparrow");
431let result = treeSet.popFirst();
432```
433
434
435### popLast
436
437popLast(): T
438
439Removes the last element in this container.
440
441**Atomic service API**: This API can be used in atomic services since API version 12.
442
443**System capability**: SystemCapability.Utils.Lang
444
445**Return value**
446
447| Type| Description|
448| -------- | -------- |
449| T | Element removed. If nothing is obtained, **undefined** is returned.|
450
451**Error codes**
452
453For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
454
455| ID| Error Message|
456| -------- | -------- |
457| 10200011 | The popLast method cannot be bound. |
458
459**Example**
460
461```ts
462let treeSet : TreeSet<string> = new TreeSet();
463treeSet.add("squirrel");
464treeSet.add("sparrow");
465let result = treeSet.popLast();
466```
467
468
469### clear
470
471clear(): void
472
473Clears this container and sets its length to **0**.
474
475**Atomic service API**: This API can be used in atomic services since API version 12.
476
477**System capability**: SystemCapability.Utils.Lang
478
479**Error codes**
480
481For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
482
483| ID| Error Message|
484| -------- | -------- |
485| 10200011 | The clear method cannot be bound. |
486
487**Example**
488
489```ts
490let treeSet : TreeSet<string> = new TreeSet();
491treeSet.add("squirrel");
492treeSet.add("sparrow");
493treeSet.clear();
494```
495
496
497### values
498
499values(): IterableIterator&lt;T&gt;
500
501Obtains an iterator that contains all the values in this container.
502
503**Atomic service API**: This API can be used in atomic services since API version 12.
504
505**System capability**: SystemCapability.Utils.Lang
506
507**Return value**
508
509| Type| Description|
510| -------- | -------- |
511| IterableIterator&lt;T&gt; | Iterator obtained.|
512
513**Error codes**
514
515For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
516
517| ID| Error Message|
518| -------- | -------- |
519| 10200011 | The values method cannot be bound. |
520
521**Example**
522
523```ts
524let treeSet : TreeSet<string> = new TreeSet();
525treeSet.add("squirrel");
526treeSet.add("sparrow");
527let it = treeSet.values();
528let t: IteratorResult<string> = it.next();
529while(!t.done) {
530  console.log("TreeSet: " + t.value);
531  t = it.next()
532}
533```
534
535
536### forEach
537
538forEach(callbackFn: (value?: T, key?: T, set?: TreeSet&lt;T&gt;) => void, thisArg?: Object): void
539
540Uses a callback to traverse the elements in this container and obtain their position indexes.
541
542**Atomic service API**: This API can be used in atomic services since API version 12.
543
544**System capability**: SystemCapability.Utils.Lang
545
546**Parameters**
547
548| Name| Type| Mandatory| Description|
549| -------- | -------- | -------- | -------- |
550| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.|
551| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked. The default value is this instance.|
552
553callbackFn
554| Name| Type| Mandatory| Description|
555| -------- | -------- | -------- | -------- |
556| value | T | No| Value of the element that is currently traversed. The default value is the value of the first key-value pair.|
557| key | T | No| Key of the element that is currently traversed. The default value is the key of the first key-value pair.|
558| set | TreeSet&lt;T&gt; | No| Instance that calls the **forEach** API. The default value is this instance.|
559
560**Error codes**
561
562For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md).
563
564| ID| Error Message|
565| -------- | -------- |
566| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
567| 10200011 | The forEach method cannot be bound. |
568
569**Example**
570
571```ts
572let treeSet : TreeSet<string> = new TreeSet();
573treeSet.add("sparrow");
574treeSet.add("gull");
575treeSet.forEach((value ?: string, key ?: string) :void => {
576  console.log("value:" + value, "key:" + key);
577});
578```
579```ts
580// You are not advised to use the set or remove APIs in forEach because they may cause unpredictable risks such as infinite loops. You can use the for loop when inserting or deleting data.
581let treeSet : TreeSet<string> = new TreeSet();
582for(let i = 0; i < 10; i++) {
583  treeSet.add("sparrow" + i);
584}
585for(let i = 0; i < 10; i++) {
586  treeSet.remove("sparrow" + i);
587}
588```
589
590### entries
591
592entries(): IterableIterator<[T, T]>
593
594Obtains an iterator that contains all the elements in this container.
595
596**Atomic service API**: This API can be used in atomic services since API version 12.
597
598**System capability**: SystemCapability.Utils.Lang
599
600**Return value**
601
602| Type| Description|
603| -------- | -------- |
604| IterableIterator<[T, T]> | Iterator obtained.|
605
606**Error codes**
607
608For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
609
610| ID| Error Message|
611| -------- | -------- |
612| 10200011 | The entries method cannot be bound. |
613
614**Example**
615
616```ts
617let treeSet : TreeSet<string> = new TreeSet();
618treeSet.add("squirrel");
619treeSet.add("sparrow");
620let it = treeSet.entries();
621let t: IteratorResult<Object[]> = it.next();
622while(!t.done) {
623  console.log("TreeSet: " + t.value);
624  t = it.next()
625}
626```
627```ts
628// You are not advised to use the set or remove APIs in entries because they may cause unpredictable risks such as infinite loops. You can use the for loop when inserting or deleting data.
629let treeSet : TreeSet<string> = new TreeSet();
630for(let i = 0; i < 10; i++) {
631  treeSet.add("sparrow" + i);
632}
633for(let i = 0; i < 10; i++) {
634  treeSet.remove("sparrow" + i);
635}
636```
637
638### [Symbol.iterator]
639
640[Symbol.iterator]\(): IterableIterator&lt;T&gt;
641
642Obtains an iterator, each item of which is a JavaScript object.
643
644**Atomic service API**: This API can be used in atomic services since API version 12.
645
646**System capability**: SystemCapability.Utils.Lang
647
648**Return value**
649
650| Type| Description|
651| -------- | -------- |
652| IterableIterator&lt;T&gt; | Iterator obtained.|
653
654**Error codes**
655
656For details about the error codes, see [Utils Error Codes](errorcode-utils.md).
657
658| ID| Error Message|
659| -------- | -------- |
660| 10200011 | The Symbol.iterator method cannot be bound. |
661
662**Example**
663
664```ts
665let treeSet : TreeSet<string> = new TreeSet();
666treeSet.add("squirrel");
667treeSet.add("sparrow");
668let numbers = Array.from(treeSet.values())
669// Method 1:
670for (let item of numbers) {
671  console.log("value:" + item);
672}
673// Method 2:
674let iter = treeSet[Symbol.iterator]();
675let temp: IteratorResult<string> = iter.next().value;
676while(temp != undefined) {
677  console.log("value:" + temp);
678  temp = iter.next().value;
679}
680```
681```ts
682// You are not advised to use the set or remove APIs in Symbol.iterator because they may cause unpredictable risks such as infinite loops. You can use the for loop when inserting or deleting data.
683let treeSet : TreeSet<string> = new TreeSet();
684for(let i = 0; i < 10; i++) {
685  treeSet.add("sparrow" + i);
686}
687for(let i = 0; i < 10; i++) {
688  treeSet.remove("sparrow" + i);
689}
690```
691